Database Schema¶
All timestamps are stored as UTC without timezone info. Coin values use Numeric(12, 6) precision.
UML Entity-Relationship Diagram¶
erDiagram
entities {
int id PK
uuid uuid UK
string entity_type
string email
string name
string initials
string gravatar_hash
bool active
bool store_conversations
int owner_entity_id FK
datetime created_at
}
api_keys {
int id PK
uuid uuid UK
int entity_id FK
string name
string key_hash
string key_hint
string key_type
datetime revoked_at
datetime expires_at
int requests
bigint input_tokens
bigint output_tokens
bigint cached_input_tokens
bigint cache_write_tokens
bigint audio_seconds
numeric cost
datetime last_used_at
datetime created_at
string client_id
string requested_by
int created_by_entity_id FK
int revoked_by_entity_id FK
}
auth_requests {
int id PK
uuid uuid UK
string flow
string client_id
string requested_name
string author
string status
datetime created_at
datetime expires_at
string device_code_hash
string user_code
datetime last_polled_at
text redirect_uri
string code_challenge
string auth_code_hash
datetime auth_code_expires_at
int entity_id FK
bool overwrite
bigint ttl
datetime approved_at
int api_key_id FK
}
model_configs {
int id PK
string model_name
numeric input_cost_per_million
numeric cached_input_cost_per_million
numeric cache_write_cost_per_million
numeric output_cost_per_million
numeric audio_cost_per_hour
int owner_entity_id FK
bool needs_ack
text ack_message
bool early_access
datetime end_date
bool disabled
text description
string url
int context_window
int max_output_tokens
bool supports_function_calling
bool supports_reasoning
json input_modalities
json output_modalities
string knowledge_cutoff
text notice
datetime created_at
}
model_endpoints {
int id PK
int model_config_id FK
string url
string api_key
string model_name
bool active
bool healthy
datetime last_checked_at
datetime created_at
}
model_aliases {
int id PK
string alias
int model_config_id FK
datetime created_at
}
entity_limits {
int id PK
int entity_id FK
numeric max_coins
numeric refresh_coins
numeric starting_coins
bool config_managed
}
entity_balances {
int id PK
int entity_id FK
numeric coins_left
datetime last_refill_at
}
entity_model_consents {
int id PK
int entity_id FK
int model_config_id FK
datetime consented_at
datetime early_access_at
}
groups {
int id PK
uuid uuid UK
string name
text description
bool active
bool auto_join
datetime created_at
}
group_members {
int id PK
int group_id FK
int entity_id FK
bool config_managed
bool is_owner
datetime joined_at
}
group_rules {
int id PK
int group_id FK
string field
string match
string value
}
group_limits {
int id PK
int group_id FK
numeric max_coins
numeric refresh_coins
numeric starting_coins
}
entity_managers {
int id PK
int user_entity_id FK
int project_entity_id FK
string role
}
model_stats {
int id PK
int entity_id FK
int model_config_id FK
string source
int requests
bigint input_tokens
bigint output_tokens
bigint cached_input_tokens
bigint cache_write_tokens
bigint audio_seconds
numeric cost
datetime last_used_at
int folded_requests
bigint folded_input_tokens
bigint folded_output_tokens
bigint folded_cached_input_tokens
bigint folded_cache_write_tokens
bigint folded_audio_seconds
numeric folded_cost
}
entity_stats {
int entity_id PK
int requests
bigint input_tokens
bigint output_tokens
bigint cached_input_tokens
bigint cache_write_tokens
bigint audio_seconds
numeric cost
int conversations
datetime last_used_at
int folded_requests
bigint folded_input_tokens
bigint folded_output_tokens
bigint folded_cached_input_tokens
bigint folded_cache_write_tokens
bigint folded_audio_seconds
numeric folded_cost
}
stats_fold_state {
int id PK
datetime cutover_at
datetime folded_until
}
conversations {
int id PK
uuid uuid UK
int entity_id FK
string title
string model
datetime created_at
datetime updated_at
}
messages {
int id PK
int conversation_id FK
string role
text content
datetime created_at
int input_tokens
int output_tokens
float time_to_first_token
float duration
float output_speed
text thinking
int thinking_tokens
}
request_logs {
bigint id PK
datetime time
int entity_id FK
int model_config_id FK
int model_endpoint_id FK
int api_key_id FK
string source
int input_tokens
int output_tokens
int cached_input_tokens
int cache_write_tokens
int audio_seconds
numeric cost
float duration
bool aborted
datetime started_at
float queue_wait
float preflight
float ttft
float ttft_visible
float send_blocked
string outcome
bool stats_deferred
}
entities ||--o{ api_keys : "owns"
entities |o--o{ api_keys : "created"
entities |o--o{ api_keys : "revoked"
entities |o--o{ auth_requests : "approves"
api_keys |o--o{ auth_requests : "minted at claim"
api_keys |o--o{ request_logs : "used by"
entities ||--o| entity_limits : "has"
entities ||--o| entity_balances : "has"
entities ||--o{ model_configs : "owns"
entities ||--o{ entity_model_consents : "consents"
entities ||--o{ model_stats : "accumulates"
entities ||--o| entity_stats : "totals"
entities ||--o{ conversations : "owns"
entities ||--o{ group_members : "belongs to"
entities ||--o{ request_logs : "logs"
entities ||--o{ entity_managers : "manages (user)"
entities ||--o{ entity_managers : "managed by (project)"
entity_managers |o--o| entities : "owns (project owner)"
groups ||--o{ group_members : "contains"
groups ||--o{ group_rules : "auto-join rules"
groups ||--o| group_limits : "has"
model_configs ||--o{ model_endpoints : "served by"
model_configs ||--o{ model_aliases : "versioned as"
model_configs ||--o{ entity_model_consents : "consented via"
model_configs ||--o{ model_stats : "accumulates"
model_configs ||--o{ request_logs : "logs"
model_endpoints ||--o{ request_logs : "logs"
conversations ||--o{ messages : "contains"
Tables¶
- entities
- api_keys
- auth_requests
- model_configs
- model_endpoints
- model_aliases
- entity_limits
- entity_balances
- entity_model_consents
- groups
- group_members
- group_rules
- group_limits
- entity_managers
- model_stats
- entity_stats
- stats_fold_state
- conversations
- messages
- request_logs
- request_counts_hourly (continuous aggregate)
- request_counts_hourly_by_entity (continuous aggregate)
- request_counts_daily (continuous aggregate)
- request_counts_hourly_total (continuous aggregate)
- request_counts_daily_by_entity (continuous aggregate)
- request_metrics_1m (continuous aggregate)
Public UUIDs¶
entities, api_keys, auth_requests, groups and conversations each have a uuid column, the only id a user ever sees. The app sets uuid4() on every insert. On PostgreSQL the column also has the database default gen_random_uuid(), so rows inserted without a uuid still get one: 2.3.1 pods during a rolling helm upgrade, or manual SQL. SQLite has no such default.
entities¶
Unified table for both human users (authenticated via OAuth) and programmatic projects (authenticated via API keys). The entity_type column distinguishes them; a third type, 'ghost', is the single shared entity that erased users are merged into (see Erasing a user).
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
uuid |
Uuid | NO | Opaque public identifier, random per row (uuid4()), with a gen_random_uuid() database default (see Public UUIDs). The only id a user ever sees (URLs, API payloads, CLI, session); for external use only, never a key or join column. Unique index ix_entities_uuid. |
entity_type |
String(8) | NO | 'user' for human users, 'project' for API projects, 'ghost' for the single shared erased-user entity |
email |
String(256) | YES | Email address; populated for users, null for projects. Unique across users. |
name |
String(256) | NO | Display name |
initials |
String(4) | NO | Short initials used in UI avatars |
gravatar_hash |
String(64) | YES | MD5 hash of the user's email for Gravatar lookups; users only |
active |
Boolean | NO | Whether the entity can make requests. Inactive entities are blocked. |
store_conversations |
Boolean | NO | Whether webchat conversations are persisted for this user. Default true. |
owner_entity_id |
Integer (FK → entity_managers) | YES | Owning user of a project; required for projects, null for users. Together with id it references the owner's entity_managers row, so the owner is always one of the project's managers. |
created_at |
DateTime | NO | UTC timestamp when the entity was created |
Constraints:
- ck_entities_type — CHECK (entity_type IN ('user', 'project', 'ghost')). PostgreSQL only.
- uq_entities_single_ghost — partial unique index ON entities (entity_type) WHERE entity_type = 'ghost': at most one ghost row. Both dialects.
- ck_entities_project_owner — CHECK ((entity_type = 'project' AND owner_entity_id IS NOT NULL) OR (entity_type <> 'project' AND owner_entity_id IS NULL)): every project has exactly one owner and users have none.
- fk_entities_owner_membership — FOREIGN KEY (owner_entity_id, id) REFERENCES entity_managers (user_entity_id, project_entity_id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED. The owner's manager row cannot be deleted while they own the project (transfer ownership first). Deferred so a project and its owner's manager row can be inserted in the same transaction. Not enforced on SQLite, which runs without foreign keys.
Notes:
- All foreign keys that reference entities.id cascade on delete, except model_configs.owner_entity_id, api_keys.created_by_entity_id and api_keys.revoked_by_entity_id, which use SET NULL, and request_logs.entity_id, which uses RESTRICT: an entity with request history cannot be deleted (see request_logs).
- Acknowledgement (needs_ack) is a property of the model, not of the entity.
- Deleting a user who owns a project fails on fk_entities_owner_membership; transfer ownership first.
- The ghost (entity_type = 'ghost', name Erased user) has no email, is inactive, and has no memberships, balance or limits. flask erase-entity creates it on first use; the migration does not seed it. Login and every user listing filter on entity_type = 'user', so it never signs in and never appears next to real users.
api_keys¶
API keys that entities (users or projects) use to authenticate against the proxy API. Keys are stored only as an HMAC-SHA256 hash; the plaintext is shown once at creation.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
uuid |
Uuid | NO | Opaque public identifier, random per row (uuid4()), with a gen_random_uuid() database default (see Public UUIDs). The only id a user ever sees (URLs, API payloads, CLI, session); for external use only, never a key or join column. Unique index ix_api_keys_uuid. |
entity_id |
Integer (FK → entities) | NO | The entity that owns this key. Cascades on delete. |
name |
String(128) | NO | Human-readable label for the key (e.g., "Production bot") |
key_hash |
String(64) | NO | HMAC-SHA256 of the raw key, keyed on ENCRYPTION_KEY; finding a key from its raw value takes the server secret. Unique. Erasure replaces it with 64 random hex characters. |
key_hint |
String(32) | YES | Last few characters of the raw key shown in the UI for identification |
key_type |
String(16) | NO | normal (default), admin or monitoring; the column, never the key prefix, decides what the key may do. A normal key uses the proxy API and is billed. Admin and monitoring keys are never billed and are refused on the proxy routes and /v1/usage (403); both list every active model on /v1/models with ?tokens=true metrics, and only an admin key may use the admin API. They work only while their owner is active and in the admins list (401 otherwise), and their last_used_at is updated at most once a minute. Existing keys, including project and OAuth keys, were set to normal by migration b7c9d1e3f5a7. |
revoked_at |
DateTime | YES | UTC time the key was revoked; null while the key is usable. Approximate (last_used_at, else created_at, else the migration time) for keys revoked before this column existed. |
expires_at |
DateTime | YES | UTC time the key expires; null if it never expires. Set when the key is created, from the chosen TTL (capped by and defaulting to api.keys.ttl; for OAuth keys, the approved auth_requests.ttl counted from mint, including when an OAuth overwrite refreshes the key in place), and when its expiry is edited. A background job (and the API on use) revokes an overdue key by setting revoked_at to this value, with revoked_by_entity_id left null. Indexed (ix_api_keys_expires_at). |
requests |
Integer | NO | Cumulative request count made with this key |
input_tokens |
BigInteger | NO | Cumulative input tokens consumed via this key |
output_tokens |
BigInteger | NO | Cumulative output tokens produced via this key |
cached_input_tokens |
BigInteger | NO | Cumulative cached input tokens among input_tokens via this key; requests whose upstream reported no cache breakdown add nothing |
cache_write_tokens |
BigInteger | NO | Cumulative prompt-cache write tokens among input_tokens via this key; requests whose upstream reports no write count add nothing |
audio_seconds |
BigInteger | NO | Cumulative seconds of audio transcribed/translated via this key |
cost |
Numeric(12,6) | NO | Cumulative cost in USD charged through this key |
last_used_at |
DateTime | YES | UTC timestamp of the most recent request; null if never used |
created_at |
DateTime | NO | UTC timestamp when the key was created |
client_id |
String(128) | YES | Application label the key was requested through via the OAuth flows; null for keys created on the profile page |
requested_by |
String(128) | YES | Requester-supplied author label from the OAuth request (unverified) |
created_by_entity_id |
Integer (FK → entities) | YES | The user who created this key (the approving user for OAuth claims). Null for legacy keys; SET NULL on creator deletion. |
revoked_by_entity_id |
Integer (FK → entities) | YES | The user who revoked this key (the approving user when an OAuth overwrite revokes an extra key with the same name). Null while the key is usable, for keys revoked before this column existed, for system revocations (OAuth authorization-code replay, key expiry), and when the revoker is deleted (SET NULL). |
Constraints: UNIQUE(key_hash); CHECK ck_api_keys_key_type (key_type IN ('normal', 'admin', 'monitoring')); index ix_api_keys_entity_id on (entity_id); index ix_api_keys_expires_at on (expires_at)
Storage: fillfactor = 80 (PostgreSQL only) so the per-request counter updates stay HOT; see migration d3e4f5a6b7c8.
auth_requests¶
Pending or handled API-key requests created by the OAuth device flow (/oauth/device_authorization) or authorization-code flow (/oauth/authorize). Secrets are stored only as SHA-256 hashes. Rows are purged by a background janitor a few minutes after expires_at.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
uuid |
Uuid | NO | Opaque public identifier, random per row (uuid4()), with a gen_random_uuid() database default (see Public UUIDs). The only id a user ever sees (URLs, API payloads, CLI, session); for external use only, never a key or join column. Unique index ix_auth_requests_uuid. |
flow |
String(16) | NO | Request flow: device or code |
client_id |
String(128) | NO | Free-form application label supplied by the requester (unverified) |
requested_name |
String(128) | NO | Name the requester wants for the API key |
author |
String(128) | YES | Free-form requester label supplied by the request (unverified) |
status |
String(16) | NO | pending, approved, denied, or claimed |
created_at |
DateTime | NO | UTC creation timestamp |
expires_at |
DateTime | NO | UTC functional expiry; approval may extend it by the claim window |
device_code_hash |
String(64) | YES | SHA-256 hash of the device-flow polling secret. Unique. |
user_code |
String(9) | YES | Human-echoed XXXX-XXXX confirmation code shown on the consent page (cannot fetch a key). Unique among pending rows (partial index). |
last_polled_at |
DateTime | YES | UTC timestamp of the most recent token poll; drives slow_down |
redirect_uri |
Text | YES | Code-flow destination the user approved; must match exactly at redemption |
code_challenge |
String(128) | YES | Code-flow S256 challenge binding redemption to the client that holds the verifier |
auth_code_hash |
String(64) | YES | SHA-256 hash of the short-lived authorization code, set at approval. Unique. |
auth_code_expires_at |
DateTime | YES | UTC expiry of the authorization code (60s after approval) |
entity_id |
Integer (FK → entities) | YES | Approving entity; set at approval. Cascades on delete. |
overwrite |
Boolean | NO | Approver agreed to replace an existing same-name key (executed at mint). Default false. |
ttl |
BigInteger | YES | Key TTL in seconds (0 = never): the ttl the request asked for (null if none), replaced at approval by the approver's choice, checked against the api.keys.ttl cap. The minted key's expires_at is mint time plus this. |
approved_at |
DateTime | YES | UTC approval timestamp |
api_key_id |
Integer (FK → api_keys) | YES | Key minted at claim; retained to revoke on authorization-code replay. SET NULL on key delete. |
Notes:
- Device flow: device_code_hash + user_code populated at creation; auth_code_* columns stay null. Code flow is the mirror image.
- A claimed request whose minted key is later deleted keeps api_key_id null (SET NULL).
model_configs¶
Configuration and metadata for each AI model that Lumen can proxy. One row per logical model name (e.g., gpt-4o). Actual backend connectivity is in model_endpoints.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
model_name |
String(128) | NO | Canonical model identifier sent to clients (e.g., gpt-4o). Unique. |
input_cost_per_million |
Numeric(12,6) | NO | USD cost per one million input tokens |
cached_input_cost_per_million |
Numeric(12,6) | YES | USD cost per one million cached input tokens; NULL uses input_cost_per_million (zero is a valid rate). Cache reads only — writes are priced by cache_write_cost_per_million. The cached token count itself is stored per request in request_logs.cached_input_tokens and folded into the stats totals; the continuous aggregates do not carry it yet. |
cache_write_cost_per_million |
Numeric(12,6) | YES | USD cost per one million prompt-cache write tokens; NULL means 0 (cache writes are free). Writes and reads are priced independently; the written count is stored per request in request_logs.cache_write_tokens and folded into the stats totals. |
output_cost_per_million |
Numeric(12,6) | NO | USD cost per one million output tokens |
audio_cost_per_hour |
Numeric(12,6) | YES | USD cost per hour of audio; only set for speech-to-text (ASR) models |
owner_entity_id |
Integer (FK → entities) | YES | Owning user entity; NULL = available to everyone. When set, only the owner may use the model. SET NULL on delete — deleting the owner makes the model public again. |
needs_ack |
Boolean | NO | Requires user acknowledgement before use; a sticky model-level property that no scope can add or remove. Default false. |
ack_message |
Text | YES | Per-model acknowledgement message; overrides the global defaults.models.ack_message. |
early_access |
Boolean | NO | Early-access model: users must acknowledge it may change or be removed before use. A sticky model-level property like needs_ack. Default false. |
end_date |
DateTime | YES | Naive-UTC datetime after which the model is hidden everywhere and rejected (exclusive comparison). NULL = no end date. |
disabled |
Boolean | NO | Hard off: the model is hidden everywhere and not overridable by any scope. Default false. |
description |
Text | YES | Human-readable description shown in the UI |
url |
String(512) | YES | Link to the model's documentation or provider page |
supports_function_calling |
Boolean | YES | Whether the model supports tool/function-calling |
input_modalities |
JSON | YES | List of supported input types, e.g., ["text", "image"] |
output_modalities |
JSON | YES | List of supported output types, e.g., ["text"] |
context_window |
Integer | YES | Total context window in tokens (input + output) |
max_output_tokens |
Integer | YES | Maximum tokens the model can generate in a single response |
supports_reasoning |
Boolean | YES | Whether the model exposes chain-of-thought / reasoning tokens |
knowledge_cutoff |
String(7) | YES | Training data cutoff in YYYY-MM format |
notice |
Text | YES | Optional admin notice, always shown in the main column of the model detail page (Markdown; use plain text or ### and lower headings) |
created_at |
DateTime | NO | UTC timestamp when the model was registered |
Notes:
- active is a derived, read-only property (active = not disabled and (end_date is null or end_date > now)), not a stored column. It replaces the old active column.
- owner_entity_id is DB-managed (edited via the model detail page), never synced from config.yaml.
model_endpoints¶
Backend endpoint(s) for a model. A single model_config can fan out to multiple endpoints for load distribution or failover. Lumen routes requests to healthy endpoints.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
model_config_id |
Integer (FK → model_configs) | NO | The model this endpoint serves. Cascades on delete. |
url |
String(256) | NO | Base URL of the backend (e.g., https://api.openai.com/v1) |
api_key |
Text | NO | Credential used when forwarding requests to this endpoint. Encrypted at rest with the app encryption key (enc:-prefixed Fernet ciphertext); the ORM decrypts transparently. |
model_name |
String(128) | YES | Override model name sent to this endpoint. When set, Lumen substitutes this value for model_config.model_name in upstream requests, enabling one Lumen model to map to differently-named backend models. |
active |
Boolean | NO | Whether the endpoint is configured for live use. Removing an endpoint from config.yaml (or deactivating its model) marks the row inactive instead of deleting it, so historical request logs keep referencing the endpoint that served them. Inactive endpoints are excluded from discovery, request routing, and health checks; re-adding the URL reactivates the row and requires a fresh health probe. |
healthy |
Boolean | NO | Last known health status; updated by the health-check background task |
last_checked_at |
DateTime | YES | UTC timestamp of the most recent health check; null if never checked |
created_at |
DateTime | NO | UTC timestamp when the endpoint was added |
model_aliases¶
Backward-compatible alias names that resolve to a canonical model_configs row. A client that requests an alias (e.g. glm-5.2) is routed to the canonical model it points at (e.g. glm-5.3-flash), so removed or renamed model IDs keep working after an upgrade. Aliases do not grant access or copy consent; the canonical model supplies all policy and capability information, so usage is recorded under the canonical model_config_id and history is preserved. See Model aliases.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
alias |
String(128) | NO | Name clients may request. Unique, and never equal to any canonical model_configs.model_name. |
model_config_id |
Integer (FK → model_configs) | NO | The canonical model this alias resolves to. Cascades on delete. |
created_at |
DateTime | NO | UTC timestamp when the alias was created |
Constraints: UNIQUE(alias); index ix_model_aliases_model_config_id on model_config_id
entity_limits¶
Budget configuration for a single entity. Each entity has at most one limit row. Coin semantics: -2 = unlimited, 0 = blocked, positive value = coin budget.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
entity_id |
Integer (FK → entities) | NO | The entity this limit applies to. Unique; one row per entity. Cascades on delete. |
max_coins |
Numeric(12,6) | NO | Maximum coins the entity may hold at any time. -2 = unlimited, 0 = blocked. |
refresh_coins |
Numeric(12,6) | NO | Coins added at each periodic refill cycle |
starting_coins |
Numeric(12,6) | NO | Coins granted when the entity is first created or reset |
config_managed |
Boolean | NO | Historical: true on rows created by the old config.yaml limit sync. Rows edited through the project/profile Edit dialogs are set to false. |
entity_balances¶
Current coin balance for each entity. Updated on every request and on each refill cycle.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
entity_id |
Integer (FK → entities) | NO | The entity this balance belongs to. Unique; one row per entity. Cascades on delete. |
coins_left |
Numeric(12,6) | NO | Current spendable coin balance |
last_refill_at |
DateTime | NO | UTC timestamp of the most recent coin refill |
Storage: fillfactor = 80 (PostgreSQL only) so the per-request counter updates stay HOT; see migration d3e4f5a6b7c8.
entity_model_consents¶
Records that an entity has acknowledged a model's requirements. A model can carry two acknowledgement requirements — needs_ack (tracked in consented_at) and early_access (tracked in early_access_at). A requirement is satisfied when its timestamp is set; if a model gains a requirement after the entity consented, the new requirement's timestamp is NULL and the entity is prompted to acknowledge again (a single combined dialog covers all outstanding requirements).
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
entity_id |
Integer (FK → entities) | NO | The consenting entity. Cascades on delete. |
model_config_id |
Integer (FK → model_configs) | NO | The model for which consent was given. Cascades on delete. |
consented_at |
DateTime | YES | UTC timestamp when the entity acknowledged the model notice (needs_ack); NULL if never required |
early_access_at |
DateTime | YES | UTC timestamp when the entity acknowledged the early-access warning; NULL if never required |
Constraints: UNIQUE(entity_id, model_config_id)
groups¶
Named collections of entities used for bulk policy assignment. Groups are managed entirely in the database via the Groups pages; a group with auto_join assigns membership at OAuth login to users matching all of its group_rules.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
uuid |
Uuid | NO | Opaque public identifier, random per row (uuid4()), with a gen_random_uuid() database default (see Public UUIDs). The only id a user ever sees (URLs, API payloads, CLI, session); for external use only, never a key or join column. Unique index ix_groups_uuid. |
name |
String(128) | NO | Unique group identifier (e.g., faculty, students) |
description |
Text | YES | Optional human-readable description shown in the admin UI |
active |
Boolean | NO | Whether the group is currently in effect |
auto_join |
Boolean | NO | When true, users matching all of the group's rules are added as members at OAuth login |
created_at |
DateTime | NO | UTC timestamp when the group was created |
group_members¶
Association table linking entities to groups. An entity may belong to multiple groups.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
group_id |
Integer (FK → groups) | NO | The group. Cascades on delete. |
entity_id |
Integer (FK → entities) | NO | The entity that belongs to the group. Cascades on delete. |
config_managed |
Boolean | NO | When true, assigned automatically at login by the group's auto-join rules; reconciled (added/removed) at each login. Manual memberships are false. |
is_owner |
Boolean | NO | True for the group owner; at most one owner per group (enforced by app logic). The owner may add/remove members, transfer ownership, and deactivate the group. |
joined_at |
DateTime | YES | UTC timestamp when the membership was created; NULL for memberships that predate the column (join time unknown) |
Constraints: UNIQUE(group_id, entity_id)
group_rules¶
Auto-join conditions per group, edited on the group detail page (admin-only Rules tab). A user matching all of a group's rules is added as a member at OAuth login; a group with auto_join but no rules matches nobody (fails closed).
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
group_id |
Integer (FK → groups) | NO | The group this rule belongs to. Cascades on delete. |
field |
String(128) | NO | Userinfo claim to inspect (e.g. affiliation, idp) |
match |
String(8) | NO | contains for substring match, equals for exact match |
value |
String(256) | NO | Value the claim is compared against |
Constraints: index on group_id
group_limits¶
Coin budget configuration for a group. Works identically to entity_limits but applies to all members of the group unless overridden at the entity level.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
group_id |
Integer (FK → groups) | NO | The group this limit applies to. Unique; one row per group. Cascades on delete. |
max_coins |
Numeric(12,6) | NO | Maximum coins the group may hold at any time. -2 = unlimited, 0 = blocked. |
refresh_coins |
Numeric(12,6) | NO | Coins added at each periodic refill cycle |
starting_coins |
Numeric(12,6) | NO | Coins granted when the group is first created or reset |
entity_managers¶
Maps users to the project entities they are members of. role is 'manager' or 'user'. A manager can view and administer a project's API keys and usage. The project owner is the member that entities.owner_entity_id points at — a manager who can additionally add/remove managers, transfer ownership, and activate/deactivate the project. get_project_role() in lumen/models/entity_manager.py returns 'owner', 'manager', 'user', or None for a non-member.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
user_entity_id |
Integer (FK → entities) | NO | The member user (must be entity_type = 'user'); their rights depend on role. Cascades on delete. |
project_entity_id |
Integer (FK → entities) | NO | The project the user is a member of. Cascades on delete. |
role |
String(16) | NO | Project role: 'manager' or 'user'. Defaults to 'manager'; rows that existed before the column was added are managers. The owner keeps their own row (normally 'manager') — ownership is the entities.owner_entity_id pointer, not a role value. |
Constraints: UNIQUE(user_entity_id, project_entity_id), also the target of entities.fk_entities_owner_membership; ck_entity_managers_role — CHECK (role IN ('manager', 'user'))
model_stats¶
Running aggregated usage counters per entity per model per source, folded from request_logs by the stats fold (see stats_fold_state); before the stats cutover, billing bumps them on every proxied request instead. Used for the usage dashboard.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
entity_id |
Integer (FK → entities) | NO | The entity that made the requests. Cascades on delete. |
model_config_id |
Integer (FK → model_configs) | NO | The model used. Cascades on delete. |
source |
String(8) | NO | Origin of the request: 'chat' (web UI) or 'api' (API key) |
requests |
Integer | NO | Total number of requests |
input_tokens |
BigInteger | NO | Total input tokens consumed |
output_tokens |
BigInteger | NO | Total output tokens produced |
cached_input_tokens |
BigInteger | NO | Total cached input tokens among input_tokens, folded from request_logs.cached_input_tokens; requests whose upstream reported no cache breakdown add nothing |
cache_write_tokens |
BigInteger | NO | Total prompt-cache write tokens among input_tokens, folded from request_logs.cache_write_tokens; requests whose upstream reports no write count add nothing; writes are billed only from a count the backend reports (see Pricing) |
audio_seconds |
BigInteger | NO | Total seconds of audio transcribed/translated |
cost |
Numeric(12,6) | NO | Total cost in USD |
last_used_at |
DateTime | NO | UTC timestamp of the most recent request counted in this row |
folded_requests |
Integer | NO | Part of requests added by the stats fold since the cutover; flask check-stats compares it with request_logs |
folded_input_tokens |
BigInteger | NO | Part of input_tokens added by the stats fold since the cutover |
folded_output_tokens |
BigInteger | NO | Part of output_tokens added by the stats fold since the cutover |
folded_cached_input_tokens |
BigInteger | NO | Part of cached_input_tokens added by the stats fold since the cutover |
folded_cache_write_tokens |
BigInteger | NO | Part of cache_write_tokens added by the stats fold since the cutover |
folded_audio_seconds |
BigInteger | NO | Part of audio_seconds added by the stats fold since the cutover |
folded_cost |
Numeric(12,6) | NO | Part of cost added by the stats fold since the cutover |
Constraints: UNIQUE(entity_id, model_config_id, source); index ix_model_stats_model_config_id on (model_config_id)
Storage: fillfactor = 80 (PostgreSQL only) so the counter updates (billing before the stats cutover, the stats fold after) stay HOT; see migration d3e4f5a6b7c8.
entity_stats¶
Pre-aggregated usage totals per entity across all models and sources. One row per entity, folded from request_logs alongside model_stats (bumped by billing on every proxied request before the stats cutover). Enables O(1) per-entity lookups in the admin users table and projects listing without scanning model_stats.
| Column | Type | Nullable | Description |
|---|---|---|---|
entity_id |
Integer (PK, FK → entities) | NO | The entity these counters belong to. Cascades on delete. |
requests |
Integer | NO | Total request count across all models and sources |
input_tokens |
BigInteger | NO | Total input tokens consumed across all models and sources |
output_tokens |
BigInteger | NO | Total output tokens produced across all models and sources |
cached_input_tokens |
BigInteger | NO | Total cached input tokens among input_tokens across all models and sources; requests whose upstream reported no cache breakdown add nothing |
cache_write_tokens |
BigInteger | NO | Total prompt-cache write tokens among input_tokens across all models and sources; requests whose upstream reports no write count add nothing |
audio_seconds |
BigInteger | NO | Total seconds of audio transcribed/translated across all models and sources |
cost |
Numeric(12,6) | NO | Total cost in USD across all models and sources |
conversations |
Integer | NO | Total webchat conversations started. Retained even when conversations are deleted or storage is disabled. |
last_used_at |
DateTime | YES | UTC timestamp of the most recent request by this entity; null if never used |
folded_requests |
Integer | NO | Part of requests added by the stats fold since the cutover; flask check-stats compares it with request_logs |
folded_input_tokens |
BigInteger | NO | Part of input_tokens added by the stats fold since the cutover |
folded_output_tokens |
BigInteger | NO | Part of output_tokens added by the stats fold since the cutover |
folded_cached_input_tokens |
BigInteger | NO | Part of cached_input_tokens added by the stats fold since the cutover |
folded_cache_write_tokens |
BigInteger | NO | Part of cache_write_tokens added by the stats fold since the cutover |
folded_audio_seconds |
BigInteger | NO | Part of audio_seconds added by the stats fold since the cutover |
folded_cost |
Numeric(12,6) | NO | Part of cost added by the stats fold since the cutover |
Notes:
- Populated on migration by a GROUP BY backfill from model_stats.
- After the stats cutover the totals lag real time by up to stats.fold_lag + stats.fold_interval (about 6 minutes by default); the user's own /profile adds their not-yet-folded request_logs on top and is exact. conversations stays synchronous: it is bumped once per new conversation, not per request.
- The folded_* columns (here and in model_stats) hold the fold's own part of each total, which flask check-stats compares with request_logs since the cutover; the totals themselves also carry history from before request_logs existed.
Storage: fillfactor = 80 (PostgreSQL only) so the counter updates (billing before the stats cutover, the stats fold after) stay HOT; see migration d3e4f5a6b7c8.
stats_fold_state¶
Single-row state of the stats fold, which adds request_logs rows into model_stats and entity_stats in windows instead of billing bumping them on every request. Before the cutover, billing bumps the counters and the fold does nothing; from cutover_at on, the fold owns every request.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key; always 1 |
cutover_at |
DateTime | YES | UTC instant from which request_logs rows are folded instead of bumped by billing; null until cutover |
folded_until |
DateTime | YES | UTC end (exclusive) of the last folded window; starts equal to cutover_at, null until cutover |
Notes:
- The migrations set the row on both dialects. On SQLite e4f5a6b7c8d9 sets both columns to the migration time. On PostgreSQL f5b6c7d8e9f0 sets both to the migration time minus one hour, unless a cutover is set already; no operator step is needed. Billing marks each row it leaves to the fold (request_logs.stats_deferred), and the fold counts only marked rows, so old pods still bumping during a rolling update are never counted twice.
- A missing row (a database built with create_all()) means the same as a null cutover_at: not cut over.
- Each fold pass covers the half-open window [folded_until, now − lag) and advances folded_until with a compare-and-set, so concurrent passes never fold a row twice.
- flask check-stats [--fix] reports (and repairs) requests the fold missed, such as a billing transaction that committed more than stats.fold_lag after its timestamp. check-stats locks this row for its whole run, and flask reassign-model around its model_stats merge, so no fold pass runs in the middle of either.
conversations¶
Chat sessions created through the Lumen web UI. Each conversation belongs to a single entity and holds an ordered list of messages. Deleting a conversation permanently removes it and all its messages.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
uuid |
Uuid | NO | Opaque public identifier, random per row (uuid4()), with a gen_random_uuid() database default (see Public UUIDs). The only id a user ever sees (URLs, API payloads, CLI, session); for external use only, never a key or join column. Unique index ix_conversations_uuid. |
entity_id |
Integer (FK → entities) | NO | The entity (user) who owns the conversation. Cascades on delete. |
title |
String(40) | NO | Short auto-generated or user-edited title |
model |
String(128) | NO | Model name used in this conversation (snapshot at creation time) |
created_at |
DateTime | NO | UTC timestamp when the conversation was created |
updated_at |
DateTime | NO | UTC timestamp of the most recent message or edit |
messages¶
Individual turns within a conversation. Both user and assistant messages are stored here.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
Integer | NO | Primary key |
conversation_id |
Integer (FK → conversations) | NO | The conversation this message belongs to. Cascades on delete. |
role |
String(16) | NO | Speaker role: 'user', 'assistant', or 'system' |
content |
Text | NO | Full message text |
created_at |
DateTime | NO | UTC timestamp when the message was created |
input_tokens |
Integer | YES | Input tokens reported by the model; assistant messages only |
output_tokens |
Integer | YES | Output tokens reported by the model; assistant messages only |
time_to_first_token |
Float | YES | Seconds from request send to first token received; assistant messages only |
duration |
Float | YES | Total response time in seconds; assistant messages only |
output_speed |
Float | YES | Output tokens per second; assistant messages only |
thinking |
Text | YES | Reasoning/thinking content from the model; assistant messages only |
thinking_tokens |
Integer | YES | Thinking/reasoning token count reported by the model; assistant messages only |
Constraints: index ix_messages_conversation_id_created_at on (conversation_id, created_at)
request_logs¶
Append-only log of every proxied request. On PostgreSQL this table is converted to a TimescaleDB hypertable partitioned by time, enabling efficient time-range queries and compression. It is never pruned: no retention policy, drop_chunks or DELETE touches it. On SQLite it behaves as a plain table.
| Column | Type | Nullable | Description |
|---|---|---|---|
id |
BigInteger | NO | Surrogate primary key (Integer on SQLite); avoids timestamp collision under concurrent load |
time |
DateTime (with timezone) | NO | UTC timestamp of the request; TimescaleDB partition key. Indexed but non-unique. |
entity_id |
Integer (FK → entities) | YES | The entity that made the request. RESTRICT on delete; NULL only on rows nulled while the FK was SET NULL |
model_config_id |
Integer (FK → model_configs) | YES | The model used. RESTRICT on delete; models are retired, never deleted |
model_endpoint_id |
Integer (FK → model_endpoints) | YES | The specific backend endpoint that served the request. RESTRICT on delete; endpoints are retired (marked inactive), never deleted, so the reference stays resolvable |
api_key_id |
Integer (FK → api_keys) | YES | The API key that made the request. NULL for chat requests and for API requests logged before this column existed (see Notes). RESTRICT on delete; keys are revoked, never deleted |
source |
String(8) | NO | Origin of the request: 'chat' or 'api' |
input_tokens |
Integer | NO | Input token count for this request |
output_tokens |
Integer | NO | Output token count for this request |
cached_input_tokens |
Integer | YES | Part of input_tokens the upstream served from its prompt cache and priced at model_configs.cached_input_cost_per_million. NULL when there is nothing to record — an aborted request with no terminal usage object, a row written before this column existed, or a usage object that reported no cache count at all — so "unknown" stays distinguishable from a reported zero (which records 0 and matches the price charged). Rows are not backfilled. |
cache_write_tokens |
Integer | YES | Part of input_tokens written to the prompt cache — the cache_creation_input_tokens count the upstream reports (or its created_cache_tokens / cache_write_tokens spelling) — priced at model_configs.cache_write_cost_per_million. Unset rate = 0 (free); writes are billed only from a count the backend reports (see Pricing), so a backend that reports none gets NULL here. NULL also when there is nothing to record (an aborted request with no terminal usage object, a row written before this column existed); a reported zero stays 0, so "unknown" is distinguishable from "none". Rows are not backfilled. |
audio_seconds |
Integer | NO | Seconds of audio transcribed/translated; 0 for text requests |
cost |
Numeric(12,6) | NO | Cost in USD for this request |
duration |
Float | NO | Total proxy response time in seconds |
aborted |
Boolean | NO | True if the client disconnected before the stream completed; token counts may be estimated |
started_at |
DateTime (with timezone) | YES | UTC instant the request arrived at the ASGI bridge (T0) |
queue_wait |
Float | YES | Seconds spent waiting for a WSGI worker thread (T1−T0) |
preflight |
Float | YES | Seconds from worker pickup to the upstream call (T2−T1) |
ttft |
Float | YES | Seconds to the first upstream chunk of any kind, including reasoning deltas |
ttft_visible |
Float | YES | Seconds to the first visible content delta |
send_blocked |
Float | YES | Seconds blocked handing response chunks to the server |
outcome |
String(16) | YES | How the request ended: 'ok' or 'disconnect' |
stats_deferred |
Boolean | YES | TRUE when billing left this request out of model_stats / entity_stats for the stats fold to add; NULL when billing counted it directly (before the stats cutover, on an older pod during a rolling update, or with a stale cached cutover). The fold, flask check-stats and the /profile live tail read only TRUE rows, so every request is counted exactly once |
Constraints: index request_logs_time_idx on (time DESC); index ix_request_logs_entity_id on (entity_id); index ix_request_logs_model_config_id_time on (model_config_id, time DESC)
Notes:
- Rows referenced by request_logs are never hard-deleted. The four foreign keys use RESTRICT on delete, so a direct DELETE of an entity, model, endpoint or API key that has request history fails. Retire or deactivate instead: models and endpoints are retired (the config sync clears model_endpoints.active, so model_endpoint_id keeps pointing at the endpoint that served each request), entities are deactivated, and API keys are revoked (revoked_at); flask erase-entity keeps an erased user's keys under the ghost. The only sanctioned hard delete of an entity is flask erase-entity (see Erasing a user), which moves the entity's request_logs rows to the ghost before deleting it.
- The FKs used to be SET NULL. On the compressed hypertable that action rewrote history: deleting a parent ran an UPDATE over every chunk, which decompresses compressed batches and aborts past timescaledb.max_tuples_decompressed_per_dml_transaction. Rows nulled that way before the switch keep their NULLs, which is why the columns stay nullable.
- A direct DELETE is cheap to refuse for a model (model_config_id is indexed on uncompressed chunks and the compression segmentby on compressed ones). For an entity or an endpoint it is slow: compressed chunks have no index on entity_id, and model_endpoint_id has none anywhere, so the check scans every chunk, decompressing in memory, before it fails. It never writes to request_logs.
- api_key_id together with source: 'api' with a value is the key that made the request; 'chat' with NULL is a web UI request, which uses no key; 'api' with NULL means the key is unknown, because the row was logged before the column existed (or by an older pod during the rolling update that added it).
- All four foreign keys are NOT VALID on PostgreSQL, on purpose, and are never validated. New rows are checked against the parent, existing rows are not, and pg_constraint.convalidated stays false. Validating would scan the whole never-pruned hypertable, decompressing every compressed chunk while holding a lock that blocks billing, and would prove nothing:
- fk_request_logs_api_key_id: the migration (c5d7e9f1a3b6) adds the column and then the foreign key with NOT VALID, and every row older than the column is NULL. api_key_id has no index, so a direct DELETE of an API key is refused only after a scan of every chunk, like an endpoint.
- request_logs_entity_id_fkey, request_logs_model_config_id_fkey and request_logs_model_endpoint_id_fkey: the switch to RESTRICT (c8d0e2f4a6b8) drops each FK and re-adds it NOT VALID. The dropped FK covered the same column and parent and had already proved every row. A later VALIDATE CONSTRAINT would not help either: the upgrade runs every revision in one transaction, so it would run under the ACCESS EXCLUSIVE lock the drop holds until commit. Databases that ran the earlier, validating form of this revision keep convalidated = true; the schema is otherwise the same.
- time is indexed by request_logs_time_idx, the index TimescaleDB creates with the hypertable (declared on the model, and created by the migration on SQLite), but not unique; concurrent workers may insert rows with the same timestamp without collision.
- Timing columns measure the user's wait, which duration does not. duration starts after preflight (model lookup, access checks, coin budget, endpoint selection, pool checkout) and ends before the billing commit, while time is stamped after that commit. So neither can be walked backwards to the moment the request arrived. Together the new columns partition the request: started_at + queue_wait + preflight + ttft_visible is when the user first sees anything.
- started_at is stored, not derived. The obvious reconstruction, time − duration − queue_wait, silently assumes preflight and the billing commit take zero time. Both grow under load, so the error is largest during exactly the burst the column exists to explain.
- started_at is the second TIMESTAMPTZ in the schema (with time), deliberately unlike the naive-UTC convention everywhere else. It exists to be subtracted from time on the same row, and mixing naive with aware in that arithmetic misbehaves on PostgreSQL. Write it with datetime.now(timezone.utc), never timeutils.utcnow().
- NULL means "not measured", not "zero". Rows written before this migration, and requests that never passed through the ASGI bridge (dev server, Flask test client), have NULL timing. They were not backfilled: nothing recorded an arrival time for them, and inventing one would produce a column that looks authoritative and is wrong for every historical row.
- outcome carries only values the code can actually write. There is deliberately no billing_error or upstream_error: the row is created inside update_stats, which only flushes, so a failing commit rolls back the very row that would have recorded the failure. Enum values are added together with the code that writes them.
- ttft and ttft_visible are both stored because on a reasoning model they differ by the whole thinking phase — which is what separates "the model was queued" from "the model was thinking".
- aborted replaces the earlier "cost = 0 identifies an abandoned stream" convention: aborted streams are now billed for what they consumed, so their cost is usually non-zero. Rows written before the column was added are all false and were not backfilled — a completed request can also cost 0 (zero-priced model, audio model with no audio_cost_per_hour, missing upstream usage, or a cost that rounds to 0 at Numeric(12,6)), so the old convention could not be applied retroactively without false positives.
- cached_input_tokens and cache_write_tokens explain the cost; the aggregates cannot yet split them. The counts are priced at model_configs.cached_input_cost_per_million / cache_write_cost_per_million and stored here so a discounted request stays distinguishable from a full-price one. The continuous aggregates that back the usage charts and the monitor's token windows do not carry them, so a cost recomputed from chart tokens × published rates overstates any request with cache reads or writes; request_logs.cost and the stats totals are authoritative.
- A NULL cache count is evidence, not noise. cached_input_tokens / cache_write_tokens are NULL only when the upstream said nothing about that side, so a model whose last day of requests carries NULLs while a cache price is configured is a model whose cache price is not billing. Lumen exposes that as cache_metrics on /v1/models?tokens=true (monitoring token) and the monitor marks the un-billed price with !.
Continuous aggregates¶
PostgreSQL only. TimescaleDB continuous aggregates over request_logs, refreshed by
background policies. They are what keeps the usage charts fast; request_logs itself is never
pruned, so every aggregate can always be recomputed from it.
The usage aggregates form a hierarchy; request_metrics_1m reads request_logs directly:
request_logs
-> request_counts_hourly_by_entity 1 hour, per entity
-> request_counts_daily_by_entity 1 day, per entity
-> request_counts_hourly 1 hour, org-wide
-> request_counts_hourly_total 1 hour, org-wide totals (heatmap)
-> request_counts_daily 1 day, org-wide
Refresh them bottom-up, child before parent. Where the child has materialised, a parent
refresh copies the child's materialised rows, not raw request_logs, so a parent refreshed before
its child copies the child's stale rows. flask reassign-model and flask erase-entity follow
AGGREGATE_REFRESH_ORDER in lumen/commands.py, and flask upgrade and seed_analytics.py
follow USAGE_AGGREGATES there; a manual flask backfill-aggregate must do the same.
All six views below are real-time: they set timescaledb.materialized_only = false, so
a query unions the materialised rows with a live scan of the raw rows newer than the
materialisation watermark. Without that — and true is the default on TimescaleDB 2.13+ — the
current bucket is missing, and a user who ran forty requests this hour sees zero.
They are views, not tables. Despite the CREATE MATERIALIZED VIEW spelling, a continuous
aggregate is a plain view (pg_class.relkind = 'v') over a hidden materialisation hypertable,
so its comment is set with COMMENT ON VIEW.
Rows older than a policy's start_offset are invisible until backfilled. Once the scheduled
policy runs, the watermark advances past them, and real-time aggregation only scans raw rows
above the watermark — so history that was never materialised silently disappears from queries.
That is why the full-history backfill is a deliberate operator command; flask check-aggregate
reports whether it has run far enough back.
request_counts_hourly¶
Org-wide hourly usage, a hierarchical aggregate over
request_counts_hourly_by_entity (migration c6e8a0b2d4f6,
177). Before that it read raw request_logs with its own refresh scan.¶
Grouped by: bucket (time_bucket('1 hour', bucket) of the child), model_config_id, source
| Column | Expression | Description |
|---|---|---|
bucket |
time_bucket('1 hour', bucket) |
Start of the hour, TIMESTAMPTZ |
model_config_id |
model_config_id |
The model used; NULL once the model is deleted |
source |
source |
'chat' or 'api' |
requests |
CAST(SUM(requests) AS BIGINT) |
Requests in the bucket |
input_tokens |
CAST(SUM(input_tokens) AS BIGINT) |
Input tokens |
output_tokens |
CAST(SUM(output_tokens) AS BIGINT) |
Output tokens |
cost |
SUM(cost) |
Cost in USD |
Refresh policy: start_offset 30 days (the child's), end_offset 3 hours, schedule_interval
1 hour. The child lags up to about two hours, so the 3-hour end_offset keeps this view's
watermark on hours the child has already materialised. Refresh is driven by the invalidation log,
so the long start_offset only recomputes hours the child rewrote. Created WITH NO DATA;
flask upgrade backfills it from the child's materialised rows.
Notes:
- Its totals equal the per-entity sums. It sums the child's rows, including the NULL
entity_id group of deleted users, so for any window of whole hours it equals the sum over
request_counts_hourly_by_entity, which equals raw request_logs. Org-wide totals do not shrink
when a user is deleted.
- Real-time over a real-time child: a request made this hour shows through this view before any
refresh.
- The CASTs keep the counts bigint; SUM of a bigint is numeric.
- The all-users /usage charts read it for the Week and Month ranges. The heatmap reads
request_counts_hourly_total instead.
request_counts_daily¶
Org-wide daily usage for the Year and All ranges, a hierarchical aggregate over
request_counts_hourly (migration c6e8a0b2d4f6, #177). Same columns
and expressions as request_counts_hourly, with bucket = time_bucket('1 day', bucket): UTC
days, whatever the session time zone. The heatmap needs the hour of day, so it reads the hourly
request_counts_hourly_total. The Year window starts at a UTC midnight (_usage_period_start) so bucket >= :start
selects whole days, for the per-entity charts too.
Refresh policy: start_offset 30 days, end_offset 1 day, schedule_interval 1 hour. Created
WITH NO DATA; flask upgrade backfills it from request_counts_hourly's materialised rows.
request_counts_hourly_total¶
Org-wide hourly totals for the all-users /usage heatmap, a hierarchical aggregate over
request_counts_hourly (migration d7f9b1c3e5a7, #429). The heatmap
needs one number per hour; the hourly view has a row per hour, model and source (about 350k a
year), this one at most 8,760. Being hourly, it serves the heatmap's hour-aligned window for every
range exactly.
Grouped by: bucket (time_bucket('1 hour', bucket) of the child) only
| Column | Expression | Description |
|---|---|---|
bucket |
time_bucket('1 hour', bucket) |
Start of the hour, TIMESTAMPTZ |
requests |
CAST(SUM(requests) AS BIGINT) |
Requests in the hour |
input_tokens |
CAST(SUM(input_tokens) AS BIGINT) |
Input tokens |
output_tokens |
CAST(SUM(output_tokens) AS BIGINT) |
Output tokens |
cost |
SUM(cost) |
Cost in USD |
Refresh policy: start_offset 30 days, end_offset 4 hours (one bucket behind the hourly
view's 3 hours, so it only copies hours its child has materialised), schedule_interval 1 hour.
Created WITH NO DATA; flask upgrade backfills it from request_counts_hourly's materialised
rows.
Notes:
- It keeps all four totals, so flask check-aggregate compares its monthly totals with the other
usage aggregates'. That comparison stops at the lowest watermark of all of them.
- Outside flask reassign-model and flask erase-entity. They refresh only the aggregates
that have the column they move; this one has neither model_config_id nor entity_id. That is
correct: moving rows to another model or entity changes no hour's totals.
No retention policy on any org-wide view.
request_counts_hourly_by_entity¶
Answers "what did this user do, and how did it feel?" — the per-entity /usage charts read it
instead of raw request_logs, so an individual's "All Time" chart does not scan every raw row
of their history. They read only this view, with no raw fallback, so history the refresh policy
never reached appears only after flask backfill-aggregate.
Grouped by: bucket (time_bucket('1 hour', time)), entity_id, model_config_id, source
| Column | Expression | Description |
|---|---|---|
bucket |
time_bucket('1 hour', time) |
Start of the hour, TIMESTAMPTZ. One hour, not one day: the heatmap does EXTRACT(HOUR FROM bucket) and a daily bucket would collapse the 7×24 grid to a single column |
entity_id |
entity_id |
The entity that made the requests; NULL once the entity is deleted |
model_config_id |
model_config_id |
The model used; NULL once the model is deleted |
source |
source |
'chat' or 'api' |
requests |
COUNT(*) |
Requests in the bucket |
input_tokens |
SUM(input_tokens) |
Input tokens |
output_tokens |
SUM(output_tokens) |
Output tokens |
cost |
SUM(cost) |
Cost in USD |
duration_sum |
SUM(duration) |
Total proxy response seconds; divide by requests for the mean |
duration_max |
MAX(duration) |
Worst response time in the bucket |
aborts |
COUNT(*) FILTER (WHERE outcome = 'disconnect') |
Client disconnects. Follows outcome, not the older aborted boolean |
ttft_count |
COUNT(ttft_visible) |
Non-null denominator for the TTFT measures |
ttft_sum |
SUM(ttft_visible) |
Total seconds to first visible content |
ttft_max |
MAX(ttft_visible) |
Worst time to first visible content |
ttft_le_0_5 … ttft_le_30 |
COUNT(*) FILTER (WHERE ttft_visible <= edge) |
Cumulative histogram at 0.5, 1, 2, 5, 10 and 30 seconds |
Refresh policy: start_offset 30 days, end_offset 1 hour, schedule_interval 1 hour.
Created WITH NO DATA; full history is materialised by the operator backfill command.
Notes:
- The ttft_le_* columns are cumulative, in the Prometheus-histogram sense: each counts
everything at or below its edge, so ttft_le_0_5 <= ttft_le_1 <= … <= ttft_le_30 <= ttft_count.
p95 is found by walking the edges and interpolating. They exist because timescaledb_toolkit
is not installed on the deployed image, so percentile_agg is unavailable.
- A NULL ttft_visible counts in none of the buckets and not in ttft_count. Rows predating
the timing columns have NULL there; counting them would make every historical bucket read as
uniformly fast.
- Cardinality is bounded by active user-hours: a student uses one or two models in an hour, so a
300-student class produces a few hundred rows per hour, not users × models × hours.
- The per-entity charts read it for the Week and Month ranges, and the heatmap reads it for every
range. The other charts read request_counts_daily_by_entity
for Year and All.
request_counts_daily_by_entity¶
Per-entity daily usage for the per-entity /usage summary, requests, tokens and models charts over
the Year and All ranges, a hierarchical aggregate over
request_counts_hourly_by_entity (migration e8a0c2d4f6b8,
429). A user's All Time chart reads a row per day, model and source instead of one per hour. The¶
Year window starts at a UTC midnight (_usage_period_start), so bucket >= :start selects whole
days. The heatmap needs the hour of day, so it stays on the hourly entity view.
Grouped by: bucket (time_bucket('1 day', bucket) of the child), entity_id,
model_config_id, source
| Column | Expression | Description |
|---|---|---|
bucket |
time_bucket('1 day', bucket) |
Start of the UTC day, TIMESTAMPTZ |
entity_id |
entity_id |
The entity that made the requests; the NULL group of deleted entities is kept, so totals equal the child's |
model_config_id |
model_config_id |
The model used |
source |
source |
'chat' or 'api' |
requests |
CAST(SUM(requests) AS BIGINT) |
Requests in the day |
input_tokens |
CAST(SUM(input_tokens) AS BIGINT) |
Input tokens |
output_tokens |
CAST(SUM(output_tokens) AS BIGINT) |
Output tokens |
cost |
SUM(cost) |
Cost in USD |
Refresh policy: start_offset 30 days, end_offset 1 day, schedule_interval 1 hour. Created
WITH NO DATA; flask upgrade backfills it from request_counts_hourly_by_entity's materialised
rows.
Notes:
- Only the four totals: the timing and TTFT measures of the child are not read per day.
- It keeps all four totals, so flask check-aggregate compares its monthly totals with the other
usage aggregates'.
- It has both model_config_id and entity_id, so flask reassign-model and flask erase-entity
refresh it after its child.
- No retention policy.
request_metrics_1m¶
Answers "what is happening right now, per model?" — a ten-minute burst is over before an hourly bucket closes, so the hourly views cannot resolve a class-start incident at all.
Grouped by: bucket (time_bucket('1 minute', time)), model_config_id, source
Same measures as request_counts_hourly_by_entity (requests, input_tokens, output_tokens,
cost, duration_sum, duration_max, aborts, ttft_count, ttft_sum, ttft_max,
ttft_le_0_5 … ttft_le_30), with the same cumulative-histogram and NULL semantics.
Refresh policy: start_offset 3 hours, end_offset 1 minute, schedule_interval 1 minute.
Created WITH NO DATA; it needs no historical backfill.
Retention: buckets older than 30 days are dropped (add_retention_policy(..., drop_after =>
INTERVAL '30 days'), #169). The refresh window never reaches back past 3 hours and no reader asks
for more than 24 hours, so nothing ever needs a dropped bucket. The policy drops only the view's own
materialised chunks; request_logs keeps every raw row.
Notes:
- Deliberately no entity_id. This view describes the shape of the load, not who caused it —
request_counts_hourly_by_entity answers the per-user question. Adding entity_id here would
multiply the row count by the size of the class in every minute, for no stated requirement.
- materialized_only = false matters more here than anywhere: with a one-minute end_offset, a
materialised-only view is by construction always at least a minute stale, which is most of the
resolution the view exists to provide.
request_logs storage lifecycle¶
Compression. request_logs has columnstore compression enabled with
compress_segmentby = 'model_config_id, source' and compress_orderby = 'time DESC', and a
policy compresses chunks older than 7 days — the same interval the chunks use, so only closed
chunks are ever compressed. The segment-by columns are exactly what the analytics queries filter
on, so compressed chunks can be pruned without being decompressed.
Nullable ADD COLUMN, ADD COLUMN … DEFAULT and ADD COLUMN … NOT NULL DEFAULT all work against
compressed chunks on TimescaleDB 2.27; only NOT NULL without a default is refused, and loudly.
The residual cost of compression is I/O — servicing an ADD COLUMN rewrites compressed chunks
across the whole window.
request_logs is never pruned. No migration, command or background job adds a retention
policy, calls drop_chunks, or deletes from it (#167); tests/unit/test_request_logs_never_pruned.py
enforces this. The one retention policy Lumen adds is on request_metrics_1m, the only target that
test allows. flask check-aggregate exits 1 if a retention policy was added to request_logs by hand.
Erasing a user (GDPR)¶
flask erase-entity <uuid> [--yes] (the user's entities.uuid; the user's email, matched ignoring case, also works but always asks for confirmation, see erase-entity) hard-deletes a user for GDPR erasure. It cannot be undone, and
on PostgreSQL it is off-hours operator work. Only users can be erased; it refuses a project, the
ghost, a user who still owns a project (transfer ownership first), and, like reassign-model, runs
only while request_logs has no retention policy.
What is deleted: the user's conversations and their messages, auth_requests,
entity_balances, entity_limits, entity_model_consents, group_members (owner rows included)
and entity_managers rows, then the entities row. The command deletes these explicitly, children
first, instead of relying on ON DELETE CASCADE: SQLite runs without foreign keys, so the same
statements then erase the same rows on both dialects, and the per-table counts it prints are the
record of the erasure. The cascades and SET NULLs stay as the backstop on PostgreSQL. A unit test
walks every foreign key into entities, conversations and api_keys so a new table cannot be
missed silently.
What moves to the ghost:
- request_logs: on PostgreSQL one chunk per transaction, oldest first, like reassign-model.
entity_id is not a segmentby column, so each chunk's UPDATE can decompress the whole chunk;
every chunk touched is recompressed. Rows logged during the walk are swept up in the final
transaction. request_counts_hourly_by_entity is then refreshed month by month from the user's
first row.
- model_stats and entity_stats: added into the ghost's rows (latest last_used_at kept); a row
the ghost has no counterpart for is re-pointed.
- model_configs the user owned: disabled and re-owned by the ghost, so ON DELETE SET NULL cannot
turn a private model public. A model still listed in config.yaml is re-enabled by the next sync
but stays unusable (only its inactive owner may use it); the command warns about it.
- api_keys: revoked (revoked_at kept if already set, revoked_by_entity_id null), renamed
ghost key, and stripped of key_hint, client_id, requested_by and created_by_entity_id.
key_hash is replaced too: the old value is an HMAC of the user's raw key, so anyone holding
ENCRYPTION_KEY could hash the old key and find the row. A random value matches no raw key under
any secret. The usage counters, created_at, last_used_at and expires_at are kept as the key's
share of the pooled history. Other entities' keys only lose created_by_entity_id /
revoked_by_entity_id where those point at the user; another user's auth_requests.api_key_id
keeps pointing at the (now ghost) key.
Groups can lose their owner. A group the user owned survives with no owner (get_group_owner
returns None) until an admin sets one; the command lists those groups.
Not covered: a pending auth_requests row has no entity_id until it is approved, so nothing
links it to the user; the janitor deletes it after it expires. Personal data outside the database
(application logs, backups, an admins: email in config.yaml) is out of scope.
How the ghost counts in usage. The ghost accumulates the usage of every erased user. System-wide
totals keep including it, so they never drop on an erasure: the all-users /usage view
(request_counts_hourly), per-model numbers, Prometheus lumen_model_*_total (a drop would read as
a counter reset) and the admin Users page header totals, which count entity_type IN ('user',
'ghost'). Everything that lists or ranks individual users filters on entity_type = 'user', so the
ghost is never listed: the admin Users table, users_total / users_active, member and owner
pickers.
Resuming. Every step is safe to re-run. Interrupted before the final transaction commits, the
user still exists, inactive, and every row belongs to the user or the ghost. The final transaction
(sweep, stats merge, models, keys, deletes, entity delete) is one commit: if the entity delete fails,
for example on a request_logs row logged after the sweep, everything in it rolls back and the
command says to re-run with the same uuid. If the aggregate refresh fails, the user is gone and its
uuid no longer resolves, so the command prints the flask backfill-aggregate runs, in refresh
order, that finish it.
RESTRICT is the safety net: request_logs.entity_id is ON DELETE RESTRICT, so a row the walk
and sweep both missed fails the final delete instead of being left pointing at nobody.
Entity Relationship Overview¶
groups ──< group_members >── entities ──< api_keys
│ │
└──< group_limits ├──< entity_limits
├──< entity_balances
├──< entity_model_consents
├──< entity_managers (user→project)
model_configs ──< model_endpoints├──< model_stats
│ ├──< conversations ──< messages
├──> entities (owner_entity_id, SET NULL)
├──< model_aliases ├──< auth_requests (approves)
│ └──< request_logs
└──< model_stats / request_logs
Access Control Evaluation Order¶
When determining whether an entity (user or project) may use a model, Lumen evaluates in this order:
- Disabled or expired —
model_configs.disabled = trueorend_datein the past → blocked, not overridable. - No owner —
model_configs.owner_entity_idis NULL → allowed (the model is available to everyone). - Entity is the owner — the entity is
owner_entity_id→ allowed. - Otherwise → blocked. Group membership never opens an owned model.
Independently, if the model has needs_ack = true or early_access = true, an allowed entity must still record acknowledgement in entity_model_consents before using the model ("needs_ack" until consent).
Coin Budget Resolution Order¶
When determining an entity's coin pool, Lumen evaluates in this priority order:
- Entity-level
entity_limitsrow → if present, use it (wins over all group limits). Set by an admin on the user or project detail page.max_coins = 0blocks the entity;max_coins = -2grants unlimited access. - Group-level
group_limitsrows → if no entity limit exists, the most generous group limit is used.-2(unlimited) beats any positive value; among positive values, the highestmax_coinswins. - No limit → access is denied (entity cannot use any model).
This mirrors the model access priority: entity-level configuration always overrides group defaults.