Resource usage tracking
Resource usage tracking gives the backend two related ways to explain resource use. It shows where saved adapters and connectors are used, and it records compute use from workflow runs so the system can report tokens, pages, cost, and run metrics by organization. It is part of the backend API platform and complements the broader backend API v2 view.
Usage domains
The resource-usage domain separates profile references from execution records. This keeps delete safety and profile screens focused on relationships, while usage records support billing, dashboards, run review, and worker lookups.
| Domain | Main question | Main result |
|---|---|---|
| Profile references | What uses this adapter or connector? | Grouped, routable references and usage counts |
| Execution usage | What resources did a run consume? | Stored token, page, cost, status, and timing data |
| Aggregation | What is the total for a run or time window? | Summed metrics and trial statistics |
References: backend/…/README.md• L1-9 backend/…/models.py• L38-139
Profile reference tracking
Profile reference tracking turns relationships to an adapter or connector into a common usage model. Providers report known references in batches, and the domain also checks blocking relations that no provider claims so delete protection and usage views stay aligned.
Reference model
Each reference identifies a group, item type, source model, item identity, display name, and optional connector role. The reference also records whether it blocks deletion and whether it is a direct item counted in the profile's usage total.
References are merged by group, model, and item identity. When one connector appears as both a workflow source and destination, the merged reference reports the both role. A workflow's deployments and pipelines remain visible as related items, but the workflow itself remains the counted use.
References: backend/…/references.py• L36-112 backend/…/constants.py• L4-48
Reference providers
Reference providers are the extension point for apps that know how a profile is used. A provider receives the profiles in scope and yields profile identities with reference objects, which lets the collector gather many profiles without one lookup per profile.
The built-in providers cover workflow tool metadata and Prompt Studio relations for adapters. They cover workflow source and destination endpoints for connectors. Providers claim the foreign-key relations they report so the generic blocking-relation safety net does not report the same relation twice.
References: backend/…/references.py• L115-149 backend/…/adapters.py• L44-176 backend/…/connectors.py• L12-46 backend/…/README.md• L56-77
Usage collection
Collection starts with one empty usage set per requested profile. It combines registered providers with unclaimed PROTECT and RESTRICT relations, then adds derived deployment and pipeline items when a detail view needs them. Profile identity matching accepts UUID and string forms while ignoring references outside the requested set.
The adapter collector matches both current adapter IDs and older adapter names inside workflow tool metadata. It reads nested JSON values rather than keys, which keeps the usage result consistent with the adapter delete guard. The connector collector adds the workflow role so callers can tell whether a connector reads, writes, or does both.
References: backend/…/references.py• L159-288 backend/…/adapters.py• L15-60 backend/…/connectors.py• L12-37
Profile usage APIs
The adapter and connector APIs expose the same usage behavior through a shared view contract. A detail request returns grouped references, while an opt-in list request adds counts and can show only unused profiles.
Detail responses
GET adapter/{id}/usage/ and GET connector/{id}/usage/ return the profile ID, a direct-use count, and groups of usage items. Connector responses also return the combined used_as role. Items that the caller cannot open remain in the result for accurate counts, but their ID and name are hidden.
The response always includes the standard groups. Workflow references can also expand to their API deployments and pipelines for the detail panel. Each item states whether it blocks deletion, so the client can explain why a profile cannot be removed.
References: backend/…/serializers.py• L21-70 backend/…/serializers.py• L72-120 backend/…/schema.py• L35-60 backend/…/urls.py• L33-65 backend/…/urls.py• L20-50
List enrichment
The profile lists remain unchanged unless with_usage=true or unused=true is present. With either flag, each row gains used_in_count, and connector rows also gain used_as; a paged response gains unused_count across all eligible rows.
The list path collects usage once from the base visible set, then applies the normal list response and pagination. This shared index makes the unused filter and the cross-page count agree. A row created or shared during the request is handled as a late row so it does not lose usage data.
References: backend/…/views.py• L24-116 backend/…/pagination.py• L12-27 backend/…/schema.py• L18-32 backend/…/views.py• L171-184 backend/…/views.py• L58-74
Execution usage records
Execution usage records capture resource use produced by workers and adapters. Each record belongs to an organization and links usage to workflow, execution, run, adapter instance, and model context without requiring the related project or prompt to remain present.
Usage record schema
The record supports two main usage types: language-model calls and embedding calls. It stores token parts, total tokens, cost, model name, operation status, error detail, and elapsed time. Language-model rows can carry a reason such as extraction, challenge, summarize, or lookup; embedding rows do not need that reason.
Project and prompt IDs are optional references that survive deletion of those objects. This lets later reports retain attribution without making usage storage depend on the life cycle of the source object.
References: backend/…/models.py• L12-32 backend/…/models.py• L38-114
Worker ingestion
Workers submit usage records in batches at execution finalization through an internal API. The request requires the adapter instance, model name, and usage type, while run context and metric fields can be supplied when available.
The backend binds every batch to the organization in request context. It rejects a batch without that context because an unscoped row would not appear in tenant reports. The write and post-write hooks run in one transaction, so a hook failure rolls back the usage rows with its related writes.
This diagram shows the worker-to-storage path and the atomic boundary around persistence.
flowchart LR
W[Worker finalization] --> B[Batch usage API]
B --> V[Validate records]
V --> O[Resolve organization]
O --> T[Atomic write]
T --> U[Usage records]
T --> H[Post-write hooks]
T --> R[Created count or error]
References: backend/…/serializers.py• L26-58 backend/…/internal_views.py• L154-214 backend/…/hooks.py• L1-27 backend/…/internal_urls.py• L20-24
Usage aggregation and access
Usage access is organization-scoped and supports both record browsing and summary views. The API can filter records by time, usage type, adapter, tag, or workflow execution, then aggregate the matching data for a run or date window.
Organization usage APIs
Authenticated organization members can list and retrieve usage records with stable ordering and pagination. Summary actions report token and cost totals for a run, aggregate prompt and completion metrics for a date range, and return trial statistics such as cost, documents processed, API calls, and ETL runs.
The internal API gives workers a narrow read path for aggregated token counts and processed pages. It avoids direct database access while keeping execution-time consumers independent from the full usage list API.
References: backend/…/views.py• L26-126 backend/…/filter.py• L12-75 backend/…/urls.py• L18-38 backend/…/internal_views.py• L33-151 backend/…/internal_urls.py• L9-24
Aggregation behavior
Run summaries add token fields and cost across all matching records. Per-model summaries group by usage type, model, and language-model reason so callers can show cost and token detail for extraction, challenge, summarize, lookup, and embedding work.
Date-window summaries use the filtered organization records and return both the totals and the selected time range. Trial statistics use subscription dates when available, then fall back to the organization's creation time and a fourteen-day window.
References: backend/…/helper.py• L26-103 backend/…/helper.py• L105-176 backend/…/helper.py• L185-218 backend/…/helper.py• L269-345
Change checklist
When these files or sections are changed, remember to consider these:
- Keep
Referencemerge rules, connector role reporting, andused_in_countaligned so detail and list views do not disagree. - When a new blocking relation gains a provider, add its claim so the generic
othergroup does not duplicate it. - When a usage field or usage type changes, update the worker batch contract, the stored record model, and every aggregation that reads the field.
- Preserve organization binding on internal writes and organization filtering on reads.
- Keep derived workflow children non-counting so deployments and pipelines do not inflate workflow usage totals.
- Keep the list usage index and pagination schema aligned when changing
with_usage,unused, orunused_countbehavior.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A usage batch has no organization context | Records are rejected instead of being written outside tenant reports | The batch endpoint requires the organization context before persistence |
| A provider reports a relation but does not claim its foreign key | The same use can appear in both the provider group and other | Provider registrations include the reported relation claims |
| A connector is used as both a source and destination | A single use must show the combined role | Reference merging maps the two roles to both |
| A caller cannot open a referenced item | A usage panel could leak an item ID or name | Serialization keeps the item but sets its ID and name to null |
| A language-model record has no usage reason | Per-model output cannot place it in a valid reason bucket | Aggregation drops the unlabeled LLM row and logs the producer error |
| A post-write hook fails | Partial usage and side-table writes would disagree | Usage persistence runs the write and hooks in one transaction |
Key files
| File | Why to read it |
|---|---|
| backend/…/references.py | Core reference model, provider registry, collection, merging, and derived workflow items |
| backend/…/adapters.py | Adapter usage sources and the workflow metadata matching rule |
| backend/…/connectors.py | Connector workflow endpoint references and source/destination roles |
| backend/…/serializers.py | Detail response shape and access-safe item serialization |
| backend/…/views.py | Shared detail and list-enrichment behavior for adapters and connectors |
| backend/…/models.py | Stored execution usage record and its reporting fields |
| backend/…/internal_views.py | Worker batch ingestion and internal aggregate reads |
| backend/…/views.py | Organization-facing usage list and summary APIs |
| backend/…/helper.py | Run, date-window, per-model, page, and trial aggregation rules |
| backend/…/README.md | Published profile-usage rules and extension contract |