Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): expose monthly self-driving usage (#129511)

Georgiy Tarasov0b8ff143beca
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index c4b6e945f96d..b787ac5347f3 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -420,6 +420,24 @@ This also applies to the organization usage/spend time-series endpoints and CSV
The billing overview, usage, and spend tools do not need a rollout flag.
API scopes and billing access checks still apply.
+The project-scoped `inbox-usage-get` tool reads `GET /api/projects/:team_id/signals/usage/?month=YYYY-MM` with `signal_usage:read`.
+Its sources include signal processing, research, and downstream implementation attributed to each report's current triggering signal; its scouts include execution costs even when no report is produced.
+Those breakdowns are additive and retain missing attribution in a null-source bucket.
+Finalized spend is grouped by UTC calendar month, with unsettled work created in that month reported separately.
+The endpoint uses `InboxUsageQueryRunner`, with a five-minute cache per canonical project and month; `as_of` identifies when the returned totals were computed.
+Source attribution uses one bulk HogQL aggregate, retaining spend when signal metadata is missing or the report is deleted.
+Report metadata reads are restricted to the reports referenced by receipts in the selected range.
+The endpoint converts `month` to an explicit UTC `DateRange`; the runner resolves it with the shared `QueryDateRange` class.
+The generic query API accepts `{"kind": "InboxUsageQuery", "dateRange": {"date_from": "2026-11-01", "date_to": "2026-12-01", "explicitDate": true}}`, including its standard async execution modes, with both `query:read` and `signal_usage:read`.
+Direct queries require `dateRange` and support standard relative dates. Bounds use UTC; `date_to` is exclusive. Use `explicitDate: true` to preserve exact end timestamps.
+Usage history starts on October 1, 2026, at 00:00 UTC. All-time queries start there; ranges crossing the cutoff are clipped, and earlier months are rejected. SQL spend records use the same cutoff on finalized_at, or created_at for unsettled work.
+Direct queries must target the canonical parent project; the usage endpoint resolves child environments after checking parent-project access.
+The response returns fractional credits as decimal strings and `pricing.usd_per_credit` for USD conversion; recorded usage includes exemptions and is not an invoice amount.
+Use `system.signal_spend` for finer queries and `system.scout_runs.spend_credits` for per-run inspection, without adding the latter to the spend records again.
+Report details expose associated scout-run costs separately because one run can contribute to several reports.
+The tool shares the `self-driving-usage-display` flag with the usage UI.
+Deploy the backend route before the MCP tool wherever this shared flag is already enabled, since MCP and Django deploy separately.
+
The underlying root billing API also supports an optional `organization_id` UUID on overview reads.
Use it when refreshing billing after a payment so another tab changing the user's current project cannot change the target.
The `billing-overview-get` tool does not expose it.
diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.ts
index db8ca7eeec0f..6e9d89affd05 100644
--- a/frontend/src/lib/agentScopes.generated.ts
+++ b/frontend/src/lib/agentScopes.generated.ts
@@ -125,6 +125,7 @@ export const AGENT_USE_CASE_SCOPES = [
'session_recording_playlist:write',
'signal_scout:read',
'signal_scout:write',
+ 'signal_usage:read',
'stamphog:read',
'stamphog:write',
'streamlit_app:read',
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 2bb4be8cd6fe..16abd366df39 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -2007,6 +2007,9 @@
{
"$ref": "#/definitions/VectorSearchQuery"
},
+ {
+ "$ref": "#/definitions/InboxUsageQuery"
+ },
{
"$ref": "#/definitions/UsageMetricsQuery"
},
@@ -10311,6 +10314,107 @@
],
"type": "object"
},
+ "CachedInboxUsageQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "cache_key": {
+ "type": "string"
+ },
+ "cache_target_age": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "calculation_trigger": {
+ "description": "What triggered the calculation of the query, leave empty if user/immediate",
+ "type": "string"
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_scan": {
+ "$ref": "#/definitions/QueryScanSummary",
+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "$ref": "#/definitions/InboxUsage"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "cache_key",
+ "is_cached",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone"
+ ],
+ "type": "object"
+ },
"CachedInsightActorsQueryOptionsResponse": {
"additionalProperties": false,
"properties": {
@@ -30704,6 +30808,290 @@
"required": ["type"],
"type": "object"
},
+ "InboxUsage": {
+ "additionalProperties": false,
+ "properties": {
+ "as_of": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "attribution_incomplete": {
+ "description": "Missing source metadata is retained in a null-source bucket.",
+ "type": "boolean"
+ },
+ "exempt_credits": {
+ "description": "Billing-exempt subset of total_credits.",
+ "type": "string"
+ },
+ "incomplete": {
+ "type": "boolean"
+ },
+ "period_end": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "period_start": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "pricing": {
+ "$ref": "#/definitions/InboxUsagePricing"
+ },
+ "project_id": {
+ "$ref": "#/definitions/integer"
+ },
+ "scouts": {
+ "description": "Scout execution only. These totals and source totals sum to total_credits.",
+ "items": {
+ "$ref": "#/definitions/InboxUsageScout"
+ },
+ "type": "array"
+ },
+ "sources": {
+ "description": "Processing, research and implementation. Excludes scout execution.",
+ "items": {
+ "$ref": "#/definitions/InboxUsageSource"
+ },
+ "type": "array"
+ },
+ "total_credits": {
+ "description": "Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits.",
+ "type": "string"
+ },
+ "unsettled_credits": {
+ "description": "Unfinalized credits created in the selected range, excluded from total_credits.",
+ "type": "string"
+ },
+ "untracked_scout_run_count": {
+ "$ref": "#/definitions/integer"
+ }
+ },
+ "required": [
+ "as_of",
+ "attribution_incomplete",
+ "exempt_credits",
+ "incomplete",
+ "period_end",
+ "period_start",
+ "pricing",
+ "project_id",
+ "scouts",
+ "sources",
+ "total_credits",
+ "unsettled_credits",
+ "untracked_scout_run_count"
+ ],
+ "type": "object"
+ },
+ "InboxUsageCredits": {
+ "additionalProperties": false,
+ "properties": {
+ "exempt_credits": {
+ "description": "Billing-exempt subset of total_credits.",
+ "type": "string"
+ },
+ "incomplete": {
+ "type": "boolean"
+ },
+ "total_credits": {
+ "description": "Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits.",
+ "type": "string"
+ }
+ },
+ "required": ["total_credits", "exempt_credits", "incomplete"],
+ "type": "object"
+ },
+ "InboxUsagePricing": {
+ "additionalProperties": false,
+ "properties": {
+ "currency": {
+ "const": "USD",
+ "type": "string"
+ },
+ "usd_per_credit": {
+ "description": "Multiply credits by this value for recorded USD usage, before billing adjustments.",
+ "type": "string"
+ }
+ },
+ "required": ["currency", "usd_per_credit"],
+ "type": "object"
+ },
+ "InboxUsageQuery": {
+ "additionalProperties": false,
+ "properties": {
+ "dateRange": {
+ "$ref": "#/definitions/DateRange",
+ "description": "UTC date range. Use explicitDate for exact bounds; the end is exclusive."
+ },
+ "kind": {
+ "const": "InboxUsageQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "response": {
+ "$ref": "#/definitions/InboxUsageQueryResponse"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["dateRange", "kind"],
+ "type": "object"
+ },
+ "InboxUsageQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "$ref": "#/definitions/InboxUsage"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
+ "InboxUsageScout": {
+ "additionalProperties": false,
+ "properties": {
+ "display_name": {
+ "type": "string"
+ },
+ "exempt_credits": {
+ "description": "Billing-exempt subset of total_credits.",
+ "type": "string"
+ },
+ "incomplete": {
+ "type": "boolean"
+ },
+ "reports_produced": {
+ "$ref": "#/definitions/integer",
+ "description": "Distinct reports emitted by this scout; reports may be shared across scouts."
+ },
+ "run_count": {
+ "$ref": "#/definitions/integer"
+ },
+ "scout_config_id": {
+ "type": ["string", "null"]
+ },
+ "skill_name": {
+ "type": "string"
+ },
+ "total_credits": {
+ "description": "Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "display_name",
+ "exempt_credits",
+ "incomplete",
+ "reports_produced",
+ "run_count",
+ "scout_config_id",
+ "skill_name",
+ "total_credits"
+ ],
+ "type": "object"
+ },
+ "InboxUsageSource": {
+ "additionalProperties": false,
+ "properties": {
+ "exempt_credits": {
+ "description": "Billing-exempt subset of total_credits.",
+ "type": "string"
+ },
+ "implementation_credits": {
+ "type": "string"
+ },
+ "incomplete": {
+ "type": "boolean"
+ },
+ "processing_credits": {
+ "type": "string"
+ },
+ "research_credits": {
+ "type": "string"
+ },
+ "source_product": {
+ "type": ["string", "null"]
+ },
+ "source_type": {
+ "type": ["string", "null"]
+ },
+ "total_credits": {
+ "description": "Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "exempt_credits",
+ "implementation_credits",
+ "incomplete",
+ "processing_credits",
+ "research_credits",
+ "source_product",
+ "source_type",
+ "total_credits"
+ ],
+ "type": "object"
+ },
"InfinityValue": {
"enum": [999999, -999999],
"type": "number"
@@ -40945,6 +41333,7 @@
"DatabaseSchemaQuery",
"SuggestedQuestionsQuery",
"TeamTaxonomyQuery",
+ "InboxUsageQuery",
"EventTaxonomyQuery",
"ActorsPropertyTaxonomyQuery",
"TracesQuery",
@@ -49588,6 +49977,68 @@
"required": ["results"],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "$ref": "#/definitions/InboxUsage"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -51741,6 +52192,9 @@
{
"$ref": "#/definitions/VectorSearchQuery"
},
+ {
+ "$ref": "#/definitions/InboxUsageQuery"
+ },
{
"$ref": "#/definitions/UsageMetricsQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index c9667e19a619..14b392ed3245 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -188,6 +188,7 @@ export enum NodeKind {
// AI queries
SuggestedQuestionsQuery = 'SuggestedQuestionsQuery',
TeamTaxonomyQuery = 'TeamTaxonomyQuery',
+ InboxUsageQuery = 'InboxUsageQuery',
EventTaxonomyQuery = 'EventTaxonomyQuery',
ActorsPropertyTaxonomyQuery = 'ActorsPropertyTaxonomyQuery',
TracesQuery = 'TracesQuery',
@@ -294,6 +295,7 @@ export type AnyDataNode =
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -428,6 +430,7 @@ export type QuerySchema =
| VectorSearchQuery
// Customer analytics
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -7524,6 +7527,69 @@ export interface TeamTaxonomyItem {
export type TeamTaxonomyResponse = TeamTaxonomyItem[]
+export interface InboxUsageQuery extends DataNode<InboxUsageQueryResponse> {
+ kind: NodeKind.InboxUsageQuery
+ /** UTC date range. Use explicitDate for exact bounds; the end is exclusive. */
+ dateRange: DateRange
+}
+
+export interface InboxUsageCredits {
+ /** Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits. */
+ total_credits: string
+ /** Billing-exempt subset of total_credits. */
+ exempt_credits: string
+ incomplete: boolean
+}
+
+export interface InboxUsageSource extends InboxUsageCredits {
+ source_product: string | null
+ source_type: string | null
+ processing_credits: string
+ research_credits: string
+ implementation_credits: string
+}
+
+export interface InboxUsageScout extends InboxUsageCredits {
+ scout_config_id: string | null
+ skill_name: string
+ display_name: string
+ run_count: integer
+ /** Distinct reports emitted by this scout; reports may be shared across scouts. */
+ reports_produced: integer
+}
+
+export interface InboxUsage extends InboxUsageCredits {
+ project_id: integer
+ /** @format date-time */
+ period_start: string
+ /** @format date-time */
+ period_end: string
+ /** @format date-time */
+ as_of: string
+ /** Unfinalized credits created in the selected range, excluded from total_credits. */
+ unsettled_credits: string
+ untracked_scout_run_count: integer
+ /** Missing source metadata is retained in a null-source bucket. */
+ attribution_incomplete: boolean
+ /** Processing, research and implementation. Excludes scout execution. */
+ sources: InboxUsageSource[]
+ /** Scout execution only. These totals and source totals sum to total_credits. */
+ scouts: InboxUsageScout[]
+ pricing: InboxUsagePricing
+}
+
+export interface InboxUsagePricing {
+ currency: 'USD'
+ /** Multiply credits by this value for recorded USD usage, before billing adjustments. */
+ usd_per_credit: string
+}
+
+export interface InboxUsageQueryResponse extends AnalyticsQueryResponseBase {
+ results: InboxUsage
+}
+
+export type CachedInboxUsageQueryResponse = CachedQueryResponse<InboxUsageQueryResponse>
+
export interface TeamTaxonomyQuery extends DataNode<TeamTaxonomyQueryResponse> {
kind: NodeKind.TeamTaxonomyQuery
/** Number of rows to return */
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 7129d2e2c753..18833ef642e1 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -603,6 +603,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconHogQL,
inMenu: false,
},
+ [NodeKind.InboxUsageQuery]: {
+ name: 'Inbox usage',
+ icon: IconPieChart,
+ inMenu: false,
+ },
[NodeKind.UsageMetricsQuery]: {
name: 'Usage Metrics',
icon: IconPieChart,
diff --git a/posthog/api/query.py b/posthog/api/query.py
index a12b0de4d68c..249149bc3ec0 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -215,6 +215,7 @@ def _process_query_request(
# API token must hold the product scope, not just query:read, to run them through
# the generic endpoint.
_QUERY_KIND_SCOPES: dict[str, list[str]] = {
+ "InboxUsageQuery": ["query:read", "signal_usage:read"],
"AccountUsersQuery": ["query:read", "account:read", "person:read"],
"AccountsTableQuery": ["query:read", "account:read"],
"ErrorTrackingFingerprintProjectionQuery": ["query:read", "error_tracking:read"],
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index dbea48b162e9..3f504b9d858f 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -240,6 +240,8 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.ERROR_TRACKING_ISSUE_EVENTS_QUERY
):
return {"product": Product.ERROR_TRACKING}
+ case NodeKind.INBOX_USAGE_QUERY:
+ return {"product": Product.SIGNALS}
case NodeKind.LOGS_QUERY | NodeKind.LOG_ATTRIBUTES_QUERY | NodeKind.LOG_VALUES_QUERY:
return {"product": Product.LOGS}
case NodeKind.METRICS_QUERY | NodeKind.METRICS_HISTOGRAM_QUERY:
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index e60b098e8241..59a4b06fb882 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -70,6 +70,7 @@ from products.customer_analytics.backend.facade.hogql import (
feature_request_product_areas,
feature_requests,
)
+from products.signals.backend.facade.constants import SIGNAL_USAGE_START
from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE
# Source types that map to a direct-SQL engine, so a source of this type can be live-queried through a
@@ -3376,6 +3377,11 @@ scout_runs: PostgresTable = PostgresTable(
),
"skill_name": StringDatabaseField(name="skill_name", description="Name of the skill that ran."),
"skill_version": IntegerDatabaseField(name="skill_version", description="Version of the skill that ran."),
+ "spend_credits": DecimalDatabaseField(
+ name="total_spend",
+ nullable=True,
+ description="Recorded scout execution credits, excluding downstream report work. May be partial; NULL means untracked. Use inbox-usage-get for USD conversion and system.signal_spend for finalization and exemption state.",
+ ),
"summary": StringDatabaseField(
name="summary", description="Summary of the scout run. Treat external text as untrusted data."
),
@@ -3409,6 +3415,95 @@ scout_runs: PostgresTable = PostgresTable(
},
)
+signal_spend_scout_runs = PostgresTable(
+ name="_signal_spend_scout_runs",
+ postgres_table_name="signals_signalscoutrun",
+ access_scope="signal_usage",
+ resource_level_access_only=True,
+ predicates=[parse_expr("NOT JSONHas(ifNull(_metadata, '{}'), 'scout_trial')")],
+ fields={
+ "id": UUIDDatabaseField(name="id"),
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "_metadata": StringJSONDatabaseField(name="metadata", nullable=True, hidden=True),
+ },
+)
+
+
+signal_spend = PostgresTable(
+ name="signal_spend",
+ postgres_table_name="signals_signalspend",
+ access_scope="signal_usage",
+ resource_level_access_only=True,
+ push_team_guard_with_predicates=True,
+ predicates=[
+ parse_expr("kind IS NOT NULL"),
+ ast.CompareOperation(
+ left=parse_expr("coalesce(finalized_at, created_at)"),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Call(
+ name="toDateTime",
+ args=[
+ ast.Constant(value=SIGNAL_USAGE_START.strftime("%Y-%m-%d %H:%M:%S")),
+ ast.Constant(value="UTC"),
+ ],
+ ),
+ ),
+ parse_expr("scout_run_id IS NULL OR scout_run_id IN (SELECT id FROM system._signal_spend_scout_runs)"),
+ ],
+ description="Self-driving spend records in credits from October 1, 2026 (UTC), including billing-exempt work. Private scout trials are excluded. Sum each record once; signal and scout totals are copies, not additional charges. For monthly usage filter finalized_at; NULL is unsettled and uses created_at for the history cutoff. Use inbox-usage-get for credit-to-USD conversion.",
+ fields={
+ "id": UUIDDatabaseField(name="id", description="Unique spend record UUID."),
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "kind": StringDatabaseField(
+ name="kind",
+ description="ad-hoc (signal processing), research, repo_selection, scout_run, reviewer_triggered_implementation, or scout_triggered_implementation.",
+ ),
+ "credits": DecimalDatabaseField(
+ name="spend",
+ description="Recorded usage in credits, including fractional credits and exempt work. May be partial until finalized_at is set; convert with pricing.usd_per_credit from inbox-usage-get.",
+ ),
+ "signal_id": UUIDDatabaseField(
+ name="signal_id",
+ nullable=True,
+ description="Signal owning processing or research spend; joins to document_embeddings.document_id after converting the UUID to a string.",
+ ),
+ "scout_run_id": UUIDDatabaseField(
+ name="scout_run_id",
+ nullable=True,
+ description="Scout run owning execution spend; joins to system.scout_runs.id.",
+ ),
+ "report_id": UUIDDatabaseField(
+ name="report_id",
+ nullable=True,
+ description="Report owning implementation spend; joins to system.inbox_reports.id. Other kinds use signal_id or scout_run_id.",
+ ),
+ "task_run_id": UUIDDatabaseField(
+ name="task_run_id",
+ nullable=True,
+ description="Task run that incurred the spend, if any. Internal runs may be absent from system.task_runs.",
+ ),
+ "billing_exempt": BooleanDatabaseField(
+ name="billing_exempt",
+ description="Whether this recorded usage is exempt from billing. False does not guarantee an invoice charge.",
+ ),
+ "accounting_failed": BooleanDatabaseField(
+ name="accounting_failed",
+ description="Whether accounting is incomplete or failed; running tasks can also carry this flag.",
+ ),
+ "created_at": DateTimeDatabaseField(
+ name="created_at",
+ description="When the work started or its spend record was created; not the billing date.",
+ ),
+ "finalized_at": DateTimeDatabaseField(
+ name="finalized_at",
+ nullable=True,
+ description="When accounting finalized, in UTC. Use this for monthly totals; NULL means unsettled.",
+ ),
+ "updated_at": DateTimeDatabaseField(name="updated_at", description="When the spend record last changed."),
+ },
+)
+
+
scout_run_emissions: PostgresTable = PostgresTable(
name="scout_run_emissions",
postgres_table_name="signals_signalscoutemission",
@@ -3789,6 +3884,11 @@ inbox_reports: PostgresTable = PostgresTable(
fields={
"id": StringDatabaseField(name="id", description="Report UUID."),
"team_id": IntegerDatabaseField(name="team_id"),
+ "triggering_signal_id": UUIDDatabaseField(
+ name="triggering_signal_id",
+ nullable=True,
+ description="Current triggering signal used to attribute report-owned implementation spend to a source. May change when a report is researched again.",
+ ),
"title": StringDatabaseField(
name="title",
nullable=True,
@@ -4289,6 +4389,10 @@ class SystemTables(TableNode):
"scout_configs": TableNode(name="scout_configs", table=scout_configs),
"scout_run_emissions": TableNode(name="scout_run_emissions", table=scout_run_emissions),
"scout_runs": TableNode(name="scout_runs", table=scout_runs),
+ "_signal_spend_scout_runs": TableNode(
+ name="_signal_spend_scout_runs", table=signal_spend_scout_runs, hidden=True
+ ),
+ "signal_spend": TableNode(name="signal_spend", table=signal_spend),
"session_recordings": TableNode(name="session_recordings", table=session_recordings),
"source_schemas": TableNode(name="source_schemas", table=source_schemas),
"source_sync_jobs": TableNode(name="source_sync_jobs", table=source_sync_jobs),
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 71937429cbec..e16b964e38bc 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -124,6 +124,7 @@ from products.signals.backend.models import (
SignalScoutConfig,
SignalScoutEmission,
SignalScoutRun,
+ SignalSpend,
)
from products.surveys.backend.models import Survey, SurveyResponseArchive
from products.tasks.backend.facade import testing as tasks_testing
@@ -1043,6 +1044,12 @@ def _create_scout_run_emission(team: Team, label: str) -> SignalScoutEmission:
)
+def _create_signal_spend(team: Team, label: str) -> SignalSpend:
+ return SignalSpend.objects.for_team(team.pk).create(
+ team=team, kind=SignalSpend.Kind.AD_HOC, signal_id=uuid.uuid4(), spend="1.2345", finalized_at=timezone.now()
+ )
+
+
def _create_task_artifact(team: Team, label: str) -> uuid.UUID:
run = _create_task_run(team, label)
return tasks_testing.create_task_artifact(
@@ -1196,6 +1203,8 @@ SYSTEM_TABLE_FACTORIES = [
("scout_configs", _create_scout_config),
("scout_run_emissions", _create_scout_run_emission),
("scout_runs", _create_scout_run),
+ ("signal_spend", _create_signal_spend),
+ ("_signal_spend_scout_runs", _create_scout_run),
("session_recording_playlists", _create_session_recording_playlist),
("session_recordings", _create_session_recording),
("source_schemas", _create_source_schema),
@@ -1510,6 +1519,15 @@ class TestSystemTablesTaskInternalExclusionIsolation(NonAtomicBaseTest):
class TestSystemTablesInboxAccess(BaseTest):
+ @parameterized.expand([("signal_usage:read", True), ("signal_scout:read", False)])
+ def test_spend_tables_require_usage_scope(self, scope: str, expected_visible: bool) -> None:
+ psak = ProjectSecretAPIKey.objects.create(
+ team=self.team, label="spend-tables", secure_value="sha256$" + "e" * 64, scopes=[scope]
+ )
+ _, denied = _compute_system_table_access_decision(self.team, ProjectSecretAPIKeyUser(psak))
+ assert ("signal_spend" not in denied) is expected_visible
+ assert ("_signal_spend_scout_runs" not in denied) is expected_visible
+
@parameterized.expand(
[
("inbox_read", ["inbox:read"], True),
@@ -1601,15 +1619,34 @@ class TestSystemTablesScoutTrialExclusionIsolation(NonAtomicBaseTest):
SignalScoutRun.objects.for_team(self.team.pk).filter(id=trial.scout_run_id).update(
metadata={"scout_trial": {"version": 1}}
)
+ for emission in (visible, trial):
+ run = SignalScoutRun.objects.for_team(self.team.pk).get(id=emission.scout_run_id)
+ SignalSpend.objects.for_team(self.team.pk).create(
+ team=self.team,
+ kind=SignalSpend.Kind.SCOUT_RUN,
+ scout_run=run,
+ task_run_id=run.task_run_id,
+ spend="12.3456",
+ finalized_at=timezone.now(),
+ )
+ SignalScoutRun.objects.for_team(self.team.pk).filter(id=run.id).update(total_spend="12.3456")
runs = execute_hogql_query("SELECT id FROM system.scout_runs", team=self.team, user=self.user)
emissions = execute_hogql_query(
"SELECT id, run_id FROM system.scout_run_emissions", team=self.team, user=self.user
)
+ spend = execute_hogql_query(
+ "SELECT scout_run_id, credits FROM system.signal_spend", team=self.team, user=self.user
+ )
+ run_spend = execute_hogql_query(
+ "SELECT id, spend_credits FROM system.scout_runs", team=self.team, user=self.user
+ )
assert {str(row[0]) for row in runs.results} == {str(visible.scout_run_id)}
assert {(str(row[0]), str(row[1])) for row in emissions.results} == {
(str(visible.pk), str(visible.scout_run_id))
}
+ assert [(str(row[0]), str(row[1])) for row in spend.results] == [(str(visible.scout_run_id), "12.3456")]
+ assert [(str(row[0]), str(row[1])) for row in run_spend.results] == [(str(visible.scout_run_id), "12.3456")]
class TestSystemTablesTaskSpaceVisibilityIsolation(NonAtomicBaseTest):
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index ace6a1233b38..119b3d081e61 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -10939,6 +10939,16 @@
"table": null,
"type": "string"
},
+ "triggering_signal_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "triggering_signal_id",
+ "id": null,
+ "name": "triggering_signal_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
"title": {
"chain": null,
"fields": null,
@@ -12966,6 +12976,16 @@
"table": null,
"type": "integer"
},
+ "spend_credits": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "spend_credits",
+ "id": null,
+ "name": "spend_credits",
+ "schema_valid": true,
+ "table": null,
+ "type": "decimal"
+ },
"summary": {
"chain": null,
"fields": null,
@@ -13052,6 +13072,135 @@
"row_count": null,
"type": "system"
},
+ "system.signal_spend": {
+ "certification": null,
+ "fields": {
+ "id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "id",
+ "id": null,
+ "name": "id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "kind": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "kind",
+ "id": null,
+ "name": "kind",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "credits": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "credits",
+ "id": null,
+ "name": "credits",
+ "schema_valid": true,
+ "table": null,
+ "type": "decimal"
+ },
+ "signal_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "signal_id",
+ "id": null,
+ "name": "signal_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "scout_run_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "scout_run_id",
+ "id": null,
+ "name": "scout_run_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "report_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "report_id",
+ "id": null,
+ "name": "report_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "task_run_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "task_run_id",
+ "id": null,
+ "name": "task_run_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "billing_exempt": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "billing_exempt",
+ "id": null,
+ "name": "billing_exempt",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
+ "accounting_failed": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "accounting_failed",
+ "id": null,
+ "name": "accounting_failed",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "finalized_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "finalized_at",
+ "id": null,
+ "name": "finalized_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "updated_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "updated_at",
+ "id": null,
+ "name": "updated_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.signal_spend",
+ "name": "system.signal_spend",
+ "row_count": null,
+ "type": "system"
+ },
"system.session_recordings": {
"certification": null,
"fields": {
@@ -25915,6 +26064,16 @@
"table": null,
"type": "string"
},
+ "triggering_signal_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "triggering_signal_id",
+ "id": null,
+ "name": "triggering_signal_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
"title": {
"chain": null,
"fields": null,
@@ -27942,6 +28101,16 @@
"table": null,
"type": "integer"
},
+ "spend_credits": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "spend_credits",
+ "id": null,
+ "name": "spend_credits",
+ "schema_valid": true,
+ "table": null,
+ "type": "decimal"
+ },
"summary": {
"chain": null,
"fields": null,
@@ -28028,6 +28197,135 @@
"row_count": null,
"type": "system"
},
+ "system.signal_spend": {
+ "certification": null,
+ "fields": {
+ "id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "id",
+ "id": null,
+ "name": "id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "kind": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "kind",
+ "id": null,
+ "name": "kind",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "credits": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "credits",
+ "id": null,
+ "name": "credits",
+ "schema_valid": true,
+ "table": null,
+ "type": "decimal"
+ },
+ "signal_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "signal_id",
+ "id": null,
+ "name": "signal_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "scout_run_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "scout_run_id",
+ "id": null,
+ "name": "scout_run_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "report_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "report_id",
+ "id": null,
+ "name": "report_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "task_run_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "task_run_id",
+ "id": null,
+ "name": "task_run_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "billing_exempt": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "billing_exempt",
+ "id": null,
+ "name": "billing_exempt",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
+ "accounting_failed": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "accounting_failed",
+ "id": null,
+ "name": "accounting_failed",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "finalized_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "finalized_at",
+ "id": null,
+ "name": "finalized_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "updated_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "updated_at",
+ "id": null,
+ "name": "updated_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.signal_spend",
+ "name": "system.signal_spend",
+ "row_count": null,
+ "type": "system"
+ },
"system.session_recordings": {
"certification": null,
"fields": {
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 3e3ad93e80b9..9070619abfd7 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -66,6 +66,7 @@ from posthog.schema import (
HogQLQuery,
HogQLQueryModifiers,
HogQLVariable,
+ InboxUsageQuery,
InsightActorsQuery,
InsightActorsQueryOptions,
LifecycleQuery,
@@ -647,6 +648,7 @@ def enforce_api_queries_budget(team: Team, query: object | None = None) -> None:
RunnableQueryNode = Union[
+ InboxUsageQuery,
TrendsQuery,
FunnelsQuery,
RetentionQuery,
@@ -726,6 +728,13 @@ def get_query_runner(
user=user,
)
+ if kind == "InboxUsageQuery":
+ from products.signals.backend.facade.spend import InboxUsageQueryRunner
+
+ return InboxUsageQueryRunner(
+ query=query, team=team, timings=timings, limit_context=limit_context, modifiers=modifiers, user=user
+ )
+
if kind == "TrendsQuery":
# Check if this should use calendar heatmap runner instead
query_obj = cast(TrendsQuery | dict[str, Any], query)
diff --git a/posthog/schema.py b/posthog/schema.py
index 11380bac1b91..e906ca4079f0 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -1983,6 +1983,46 @@ class HogQueryResponse(BaseModel):
stdout: str | None = None
+class InboxUsageCredits(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ exempt_credits: str = Field(..., description="Billing-exempt subset of total_credits.")
+ incomplete: bool
+ total_credits: str = Field(
+ ...,
+ description=("Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits."),
+ )
+
+
+class InboxUsagePricing(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ currency: Literal["USD"] = "USD"
+ usd_per_credit: str = Field(
+ ...,
+ description=("Multiply credits by this value for recorded USD usage, before billing adjustments."),
+ )
+
+
+class InboxUsageSource(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ exempt_credits: str = Field(..., description="Billing-exempt subset of total_credits.")
+ implementation_credits: str
+ incomplete: bool
+ processing_credits: str
+ research_credits: str
+ source_product: str | None = None
+ source_type: str | None = None
+ total_credits: str = Field(
+ ...,
+ description=("Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits."),
+ )
+
+
class InsightsThresholdBounds(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -6475,6 +6515,26 @@ class HogQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class InboxUsageScout(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ display_name: str
+ exempt_credits: str = Field(..., description="Billing-exempt subset of total_credits.")
+ incomplete: bool
+ reports_produced: int = Field(
+ ...,
+ description=("Distinct reports emitted by this scout; reports may be shared across scouts."),
+ )
+ run_count: int
+ scout_config_id: str | None = None
+ skill_name: str
+ total_credits: str = Field(
+ ...,
+ description=("Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits."),
+ )
+
+
class DayItem(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -19641,6 +19701,86 @@ class IQRDetectorConfig(BaseModel):
)
+class InboxUsage(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ as_of: AwareDatetime
+ attribution_incomplete: bool = Field(
+ ..., description="Missing source metadata is retained in a null-source bucket."
+ )
+ exempt_credits: str = Field(..., description="Billing-exempt subset of total_credits.")
+ incomplete: bool
+ period_end: AwareDatetime
+ period_start: AwareDatetime
+ pricing: InboxUsagePricing
+ project_id: int
+ scouts: list[InboxUsageScout] = Field(
+ ...,
+ description=("Scout execution only. These totals and source totals sum to total_credits."),
+ )
+ sources: list[InboxUsageSource] = Field(
+ ...,
+ description=("Processing, research and implementation. Excludes scout execution."),
+ )
+ total_credits: str = Field(
+ ...,
+ description=("Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits."),
+ )
+ unsettled_credits: str = Field(
+ ...,
+ description=("Unfinalized credits created in the selected range, excluded from total_credits."),
+ )
+ untracked_scout_run_count: int
+
+
+class InboxUsageQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: InboxUsage
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class InsightActorsQueryBase(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -25549,7 +25689,7 @@ class QueryResponseAlternative88(BaseModel):
resolved_date_range: ResolvedDateRangeResponse | None = Field(
default=None, description="The date range used for the query"
)
- results: list[UsageMetric]
+ results: InboxUsage
timings: list[QueryTiming] | None = Field(
default=None,
description=("Measured timings for different parts of the query generation process"),
@@ -25574,6 +25714,53 @@ class QueryResponseAlternative88(BaseModel):
class QueryResponseAlternative89(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[UsageMetric]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25630,7 +25817,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25698,7 +25885,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25745,7 +25932,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25797,7 +25984,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25844,7 +26031,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25891,7 +26078,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25938,7 +26125,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25985,7 +26172,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26036,7 +26223,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26083,7 +26270,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26130,7 +26317,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26177,7 +26364,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26224,7 +26411,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26274,7 +26461,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26321,7 +26508,7 @@ class QueryResponseAlternative103(BaseModel):
)
-class QueryResponseAlternative104(BaseModel):
+class QueryResponseAlternative105(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26383,7 +26570,7 @@ class QueryResponseAlternative104(BaseModel):
)
-class QueryResponseAlternative105(BaseModel):
+class QueryResponseAlternative106(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26430,7 +26617,7 @@ class QueryResponseAlternative105(BaseModel):
)
-class QueryResponseAlternative106(BaseModel):
+class QueryResponseAlternative107(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26477,7 +26664,7 @@ class QueryResponseAlternative106(BaseModel):
)
-class QueryResponseAlternative107(BaseModel):
+class QueryResponseAlternative108(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26524,7 +26711,7 @@ class QueryResponseAlternative107(BaseModel):
)
-class QueryResponseAlternative108(BaseModel):
+class QueryResponseAlternative109(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26571,7 +26758,7 @@ class QueryResponseAlternative108(BaseModel):
)
-class QueryResponseAlternative109(BaseModel):
+class QueryResponseAlternative110(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26618,7 +26805,7 @@ class QueryResponseAlternative109(BaseModel):
)
-class QueryResponseAlternative110(BaseModel):
+class QueryResponseAlternative111(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26665,7 +26852,7 @@ class QueryResponseAlternative110(BaseModel):
)
-class QueryResponseAlternative111(BaseModel):
+class QueryResponseAlternative112(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26712,7 +26899,7 @@ class QueryResponseAlternative111(BaseModel):
)
-class QueryResponseAlternative112(BaseModel):
+class QueryResponseAlternative113(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -26760,7 +26947,7 @@ class QueryResponseAlternative112(BaseModel):
)
-class QueryResponseAlternative113(BaseModel):
+class QueryResponseAlternative114(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -28373,6 +28560,68 @@ class CachedExperimentQueryResponse(BaseModel):
)
+class CachedInboxUsageQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ query_metadata: dict[str, Any] | None = None
+ query_scan: QueryScanSummary | None = Field(
+ default=None,
+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),
+ )
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: InboxUsage
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class CachedInsightActorsQueryOptionsResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -29725,6 +29974,21 @@ class HogQLQueryResponse(BaseModel):
)
+class InboxUsageQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ dateRange: DateRange = Field(
+ ...,
+ description=("UTC date range. Use explicitDate for exact bounds; the end is exclusive."),
+ )
+ kind: Literal["InboxUsageQuery"] = "InboxUsageQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: InboxUsageQueryResponse | None = None
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class InsightActorsQueryOptionsResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -33546,6 +33810,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative111
| QueryResponseAlternative112
| QueryResponseAlternative113
+ | QueryResponseAlternative114
]
):
root: (
@@ -33659,6 +33924,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative111
| QueryResponseAlternative112
| QueryResponseAlternative113
+ | QueryResponseAlternative114
)
@@ -34792,6 +35058,7 @@ class HogQLAutocomplete(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -34937,6 +35204,7 @@ class HogQLMetadata(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35087,6 +35355,7 @@ class MaxInsightContext(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35232,6 +35501,7 @@ class QueryRequest(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35370,6 +35640,7 @@ class QuerySchemaRoot(
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35478,6 +35749,7 @@ class QuerySchemaRoot(
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35591,6 +35863,7 @@ class QueryUpgradeRequest(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35704,6 +35977,7 @@ class QueryUpgradeResponse(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
@@ -35862,6 +36136,7 @@ class VisualizationArtifactContent(BaseModel):
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
+ | InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index bc304d494e36..df586654c1c9 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2519,6 +2519,7 @@ class NodeKind(StrEnum):
DATABASE_SCHEMA_QUERY = "DatabaseSchemaQuery"
SUGGESTED_QUESTIONS_QUERY = "SuggestedQuestionsQuery"
TEAM_TAXONOMY_QUERY = "TeamTaxonomyQuery"
+ INBOX_USAGE_QUERY = "InboxUsageQuery"
EVENT_TAXONOMY_QUERY = "EventTaxonomyQuery"
ACTORS_PROPERTY_TAXONOMY_QUERY = "ActorsPropertyTaxonomyQuery"
TRACES_QUERY = "TracesQuery"
diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
index 21b60ab1539a..bd358e5c4268 100644
--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md
+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
@@ -140,6 +140,7 @@ Every column table below is generated from the live HogQL catalog, so it lists e
- [Notebooks](./references/models-notebooks.md)
- [Session Recording Playlists](./references/models-session-recording-playlists.md)
- [Session Recordings](./references/models-session-recordings.md)
+- [Self-driving usage, scout costs, and report attribution](./references/models-self-driving-usage.md)
- [Replay Vision scanners](./references/models-replay-vision.md)
- [Support Tickets](./references/models-support-tickets.md)
- [Surveys](./references/models-surveys.md)
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-self-driving-usage.md.j2 b/products/posthog_ai/skills/querying-posthog-data/references/models-self-driving-usage.md.j2
new file mode 100644
index 000000000000..51b64c0fd103
--- /dev/null
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-self-driving-usage.md.j2
@@ -0,0 +1,77 @@
+# Self-driving usage
+
+Use `inbox-usage-get` for a monthly overview by source and scout, including downstream report implementation.
+Use `execute-sql` for individual reports, runs, daily trends, or custom filters.
+The monthly tool is available when the project's rollout permits it; the SQL tables use HogQL access controls.
+
+## Spend records (`system.signal_spend`)
+
+{{ schema_columns('system.signal_spend') }}
+
+Requires usage access in the project.
+Usage history starts on October 1, 2026, at 00:00 UTC, using `finalized_at` for settled costs and `created_at` for unsettled costs.
+Each row owns one amount of recorded usage; sum these rows once.
+`credits` is a decimal, including fractional credits.
+Multiply credits by `pricing.usd_per_credit` returned by `inbox-usage-get` for the recorded USD value.
+Do not describe this value as the invoice: exemptions, billing cutovers, grants, discounts, and billing rounding can change the amount charged.
+`billing_exempt` identifies exempt recorded usage but is not a complete billability decision.
+
+Use `finalized_at` for monthly or daily usage, with an inclusive start and exclusive end in UTC.
+Unfinalized rows can still change; report them separately instead of treating their amounts as final.
+`accounting_failed` also applies to some running work, so it does not distinguish permanent failure from settling.
+The monthly tool reports unsettled work created in the requested month separately; that is not an outstanding balance across all months.
+Missing receipts are unknown costs, not zero costs.
+
+```sql
+SELECT toDate(finalized_at) AS day, kind,
+ sum(credits) AS recorded_credits,
+ sumIf(credits, billing_exempt) AS exempt_credits
+FROM system.signal_spend
+WHERE finalized_at >= toStartOfMonth(now())
+ AND finalized_at < now()
+GROUP BY day, kind
+ORDER BY day, kind
+```
+
+## Scout runs (`system.scout_runs`)
+
+{{ schema_columns('system.scout_runs') }}
+
+Requires scout access; joining spend records also requires usage access.
+`spend_credits` is a convenience copy of the run's recorded execution cost, excluding downstream report research and implementation.
+Do not add it to `system.signal_spend.credits`.
+Private scout trials are absent from both tables.
+Spend records belong to the canonical parent project.
+The monthly tool resolves a child environment to its parent, requires access to that parent, and returns the owning `project_id`.
+Use that project for SQL reconciliation.
+
+```sql
+SELECT r.skill_name, count() AS run_count, sum(s.credits) AS execution_credits
+FROM system.signal_spend s
+JOIN system.scout_runs r ON s.scout_run_id = r.id
+WHERE s.kind = 'scout_run'
+ AND s.finalized_at >= toStartOfMonth(now())
+ AND s.finalized_at < now()
+GROUP BY r.skill_name
+ORDER BY execution_credits DESC
+```
+
+Runs with no emitted reports still incur usage.
+`emitted_report_ids` can overlap between runs; deduplicate report IDs before reporting yield.
+
+## Reports and sources
+
+Signal processing (`ad-hoc`), research, and repository selection belong to `signal_id`.
+Implementation belongs to `report_id`, joining `system.inbox_reports.id` after converting the UUID to a string.
+The report's `triggering_signal_id` identifies the source to which the monthly tool attributes implementation.
+It is the current triggering signal and can change when a report is researched again; attribution is not an immutable historical invoice ledger.
+
+To resolve a signal's source, join its string ID to `document_embeddings.document_id` for product `signals`, document type `signal`, rendering `plain`, and the signals embedding model.
+Use the latest metadata version per document (`argMax(metadata, inserted_at)`) before extracting `source_product` and `source_type`; the `signals` skill has the complete signal-query patterns.
+Do not use `metadata.total_spend` as another charge: it is a cumulative copy of spend records, and grouping it by signal creation month misdates later research.
+The summary retains missing source metadata in a null-source bucket.
+Deleted reports are absent from `system.inbox_reports`, so their implementation receipts can remain readable without a report join; preserve those amounts as unattributed rather than dropping them.
+
+A report's detail shows its lifetime research/processing, implementation, and associated scout-run costs.
+The associated scout costs can be shared by multiple reports and must not be added across reports.
+For a monthly total, use the underlying spend records once: source rows contain processing/research/implementation, and scout rows contain execution.
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
index 20a18865dac1..137a1ef88d71 100644
--- a/products/signals/backend/billing.py
+++ b/products/signals/backend/billing.py
@@ -24,6 +24,7 @@ from products.signals.backend.models import (
SignalScoutRun,
SignalSpend,
)
+from products.signals.backend.pricing import SIGNALS_CREDITS_PER_DOLLAR as SIGNALS_CREDITS_PER_DOLLAR
from products.signals.backend.scout_harness.lazy_seed import scout_skill_row_is_proven_canonical
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.facade.api import GITHUB_PR_URL_PREFIX
@@ -33,7 +34,6 @@ if TYPE_CHECKING:
_IMPLEMENTATION = TASK_RUN_TYPE_IMPLEMENTATION
-SIGNALS_CREDITS_PER_DOLLAR = 100 # 1 credit = $0.01, matching ai_credits
# Flat credits charged once per report whose implementation shipped a PR ($15).
SIGNALS_CREDITS_PER_REPORT_WITH_PR = 15 * SIGNALS_CREDITS_PER_DOLLAR # 1500
diff --git a/products/signals/backend/facade/constants.py b/products/signals/backend/facade/constants.py
new file mode 100644
index 000000000000..eeec921958c2
--- /dev/null
+++ b/products/signals/backend/facade/constants.py
@@ -0,0 +1,3 @@
+from datetime import UTC, datetime
+
+SIGNAL_USAGE_START = datetime(2026, 10, 1, tzinfo=UTC)
diff --git a/products/signals/backend/facade/spend.py b/products/signals/backend/facade/spend.py
index d5b57fc112f1..000b2f8c6e67 100644
--- a/products/signals/backend/facade/spend.py
+++ b/products/signals/backend/facade/spend.py
@@ -1,5 +1,6 @@
from typing import TYPE_CHECKING
+from products.signals.backend.queries.inbox_usage_query_runner import InboxUsageQueryRunner as InboxUsageQueryRunner
from products.signals.backend.spend import (
complete_task_spend as complete_task_spend,
register_report_task_spend as register_report_task_spend,
diff --git a/products/signals/backend/facade/taxonomy.py b/products/signals/backend/facade/taxonomy.py
index 2dce2fe5215b..ca2f42a60f55 100644
--- a/products/signals/backend/facade/taxonomy.py
+++ b/products/signals/backend/facade/taxonomy.py
@@ -1,9 +1,13 @@
"""Signal taxonomy and value types that other products pass to and receive from signals."""
+from typing import TYPE_CHECKING
+
from products.signals.backend.artefact_attribution import ArtefactAttribution
-from products.signals.backend.contracts import SignalRemediation
from products.signals.backend.enums import ReportPriority, SignalSourceProduct, SignalSourceType
+if TYPE_CHECKING:
+ from products.signals.backend.contracts import SignalRemediation
+
__all__ = [
"ArtefactAttribution",
"ReportPriority",
@@ -11,3 +15,14 @@ __all__ = [
"SignalSourceProduct",
"SignalSourceType",
]
+
+
+def __getattr__(name: str) -> type["SignalRemediation"]:
+ if name != "SignalRemediation":
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+ from products.signals.backend.contracts import (
+ SignalRemediation, # noqa: PLC0415 - keeps payload schemas off Django startup
+ )
+
+ return SignalRemediation
diff --git a/products/signals/backend/presentation/spend.py b/products/signals/backend/presentation/spend.py
index 4e7066cfa912..1ab45cd2a3ef 100644
--- a/products/signals/backend/presentation/spend.py
+++ b/products/signals/backend/presentation/spend.py
@@ -1,18 +1,31 @@
from dataclasses import asdict
+from datetime import UTC, date
+from typing import TYPE_CHECKING, cast
+from django.utils import timezone
+
+from dateutil.relativedelta import relativedelta
from drf_spectacular.utils import extend_schema, extend_schema_serializer
from rest_framework import serializers, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.schema import CachedInboxUsageQueryResponse, DateRange, InboxUsageQuery
+
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.clickhouse.workload import Workload
from posthog.permissions import APIScopePermission
-from products.signals.backend.facade.spend import scout_spend_overview, source_spend_overview
+from products.signals.backend.facade.constants import SIGNAL_USAGE_START
+from products.signals.backend.facade.spend import InboxUsageQueryRunner, scout_spend_overview, source_spend_overview
from products.signals.backend.presentation.scout_permissions import ScoutCanonicalTeamAccessPermission
+if TYPE_CHECKING:
+ from posthog.models import User
+
class SpendAmountSerializer(serializers.Serializer):
total_spend = serializers.FloatField(
@@ -80,3 +93,141 @@ class SignalSourceSpendViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(responses=SourceSpendSerializer(many=True), operation_id="signals_source_spend")
def list(self, request: Request, **kwargs: object) -> Response:
return Response(SourceSpendSerializer(source_spend_overview(team=self.team), many=True).data)
+
+
+class MonthlyUsageQuerySerializer(serializers.Serializer):
+ month = serializers.RegexField(
+ r"^[0-9]{4}-(0[1-9]|1[0-2])$",
+ required=False,
+ help_text="UTC calendar month in YYYY-MM format, from 2026-10 onward. Defaults to the current month. Usage is grouped by finalization time.",
+ )
+
+ def validate_month(self, value: str) -> date:
+ try:
+ month = date.fromisoformat(f"{value}-01")
+ except ValueError:
+ raise serializers.ValidationError("Enter a valid month in YYYY-MM format.") from None
+ if month.year == 9999:
+ raise serializers.ValidationError("The year must be earlier than 9999.")
+ if month < SIGNAL_USAGE_START.date():
+ raise serializers.ValidationError("Usage is available from October 2026. Choose that month or a later one.")
+ return month
+
+
+class UsageCreditsSerializer(serializers.Serializer):
+ total_credits = serializers.DecimalField(
+ max_digits=24,
+ decimal_places=4,
+ help_text="Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.",
+ )
+ exempt_credits = serializers.DecimalField(
+ max_digits=24,
+ decimal_places=4,
+ help_text="Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.",
+ )
+ incomplete = serializers.BooleanField(help_text="Whether accounting is missing, failed, or still settling.")
+
+
+class MonthlySourceUsageSerializer(UsageCreditsSerializer):
+ source_product = serializers.CharField(
+ allow_null=True,
+ help_text="Product that emitted the signal. Null means attribution is unavailable; usage is retained.",
+ )
+ source_type = serializers.CharField(allow_null=True, help_text="Signal type within the source product.")
+ processing_credits = serializers.DecimalField(
+ max_digits=24, decimal_places=4, help_text="Credits for processing this source's signals."
+ )
+ research_credits = serializers.DecimalField(
+ max_digits=24,
+ decimal_places=4,
+ help_text="Research and repository-selection credits attributed to their triggering signals.",
+ )
+ implementation_credits = serializers.DecimalField(
+ max_digits=24,
+ decimal_places=4,
+ help_text="Implementation credits attributed to each report's current triggering signal.",
+ )
+
+
+class MonthlyScoutUsageSerializer(UsageCreditsSerializer):
+ scout_config_id = serializers.UUIDField(allow_null=True, help_text="Scout configuration UUID, if it still exists.")
+ skill_name = serializers.CharField(help_text="Scout skill name.")
+ display_name = serializers.CharField(help_text="Scout display name, falling back to its skill name.")
+ run_count = serializers.IntegerField(
+ help_text="Number of tracked scout runs whose spend finalized in this month, including runs with no reports."
+ )
+ reports_produced = serializers.IntegerField(
+ help_text="Distinct report IDs emitted by these runs. Reports can be shared across scouts; do not sum this as a project report count."
+ )
+
+
+class UsagePricingSerializer(serializers.Serializer):
+ currency = serializers.CharField(help_text="Currency of the recorded usage value: USD.")
+ usd_per_credit = serializers.DecimalField(
+ max_digits=12,
+ decimal_places=8,
+ help_text="Multiply credits by this value to get recorded usage in USD, before billing exemptions, grants, discounts, or invoice rounding.",
+ )
+
+
+@extend_schema_serializer(many=False)
+class MonthlyUsageSerializer(UsageCreditsSerializer):
+ project_id = serializers.IntegerField(
+ help_text="Canonical project that owns these spend records. A child environment resolves to its parent, which the caller must also be allowed to read."
+ )
+ period_start = serializers.DateTimeField(help_text="Inclusive start of the UTC calendar month.")
+ period_end = serializers.DateTimeField(help_text="Exclusive end of the UTC calendar month.")
+ as_of = serializers.DateTimeField(help_text="Time this summary was computed. The current month is partial.")
+ unsettled_credits = serializers.DecimalField(
+ max_digits=24,
+ decimal_places=4,
+ help_text="Recorded credits for unfinalized work created in this month, excluded from total_credits. This is not the full outstanding balance from earlier months.",
+ )
+ untracked_scout_run_count = serializers.IntegerField(
+ help_text="Public scout runs created in this month with no spend record. Their unknown costs are not counted as zero."
+ )
+ attribution_incomplete = serializers.BooleanField(
+ help_text="Whether any source attribution is missing. Unattributed credits remain in sources and total_credits."
+ )
+ sources = MonthlySourceUsageSerializer(
+ many=True,
+ help_text="Signal processing, research, and implementation grouped by source. Excludes scout execution costs.",
+ )
+ scouts = MonthlyScoutUsageSerializer(
+ many=True,
+ help_text="Scout execution costs, excluding downstream report work, which appears in sources. The sources and scouts totals sum to total_credits.",
+ )
+ pricing = UsagePricingSerializer(
+ help_text="Server-provided denomination for converting recorded credits to USD. This summary is not an invoice."
+ )
+
+
+class SignalMonthlyUsageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ serializer_class = MonthlyUsageSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission, ScoutCanonicalTeamAccessPermission]
+ scope_object = "signal_usage"
+ pagination_class = None
+
+ @validated_request(
+ query_serializer=MonthlyUsageQuerySerializer,
+ responses={200: MonthlyUsageSerializer},
+ operation_id="signals_monthly_usage",
+ )
+ def list(self, request: ValidatedRequest, **kwargs: object) -> Response:
+ month = request.validated_query_data.get("month") or timezone.now().astimezone(UTC).date().replace(day=1)
+ user = cast("User", request.user)
+ usage = InboxUsageQueryRunner(
+ query=InboxUsageQuery(
+ dateRange=DateRange(
+ date_from=month.isoformat(),
+ date_to=(month + relativedelta(months=1)).isoformat(),
+ explicitDate=True,
+ )
+ ),
+ team=self.team.parent_team or self.team,
+ user=user,
+ workload=Workload.ONLINE,
+ ).run(user=user)
+ assert isinstance(usage, CachedInboxUsageQueryResponse)
+ return Response(MonthlyUsageSerializer(usage.results).data)
diff --git a/products/signals/backend/pricing.py b/products/signals/backend/pricing.py
index 6f764a69133f..5918d54f2a71 100644
--- a/products/signals/backend/pricing.py
+++ b/products/signals/backend/pricing.py
@@ -1,8 +1,10 @@
from decimal import Decimal
+SIGNALS_CREDITS_PER_DOLLAR = 100
+
def cost_to_spend(token_cost_microusd: int, *, task_count: int = 0) -> Decimal:
"""Customer spend in USD cents: token cost plus four cents per task run."""
if token_cost_microusd < 0 or task_count < 0:
raise ValueError("Cost and task count must be nonnegative")
- return Decimal(token_cost_microusd) / 10_000 + Decimal(4) * task_count
+ return Decimal(token_cost_microusd) * SIGNALS_CREDITS_PER_DOLLAR / 1_000_000 + Decimal(4) * task_count
diff --git a/products/signals/backend/queries/inbox_usage_query_runner.py b/products/signals/backend/queries/inbox_usage_query_runner.py
new file mode 100644
index 000000000000..5a57cccf19ae
--- /dev/null
+++ b/products/signals/backend/queries/inbox_usage_query_runner.py
@@ -0,0 +1,284 @@
+from datetime import datetime, timedelta
+from decimal import Decimal
+from functools import cached_property
+from uuid import UUID
+from zoneinfo import ZoneInfo
+
+from django.db.models import Count, Exists, OuterRef, Q, QuerySet, Sum
+from django.utils import timezone
+
+from posthog.schema import (
+ CachedInboxUsageQueryResponse,
+ InboxUsage,
+ InboxUsagePricing,
+ InboxUsageQuery,
+ InboxUsageQueryResponse,
+ InboxUsageScout,
+ InboxUsageSource,
+ IntervalType,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.database.models import IntegerDatabaseField, UUIDDatabaseField
+from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.errors import QueryError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models import User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.signals.backend.facade.constants import SIGNAL_USAGE_START
+from products.signals.backend.models import SignalScoutRun, SignalSpend
+from products.signals.backend.pricing import SIGNALS_CREDITS_PER_DOLLAR
+from products.signals.backend.signal_metadata import EMBEDDING_MODEL, _deduped_signals_subquery, _signals_query_context
+
+# Deleting a report must not erase its source attribution from retained spend records.
+_SPEND_REPORTS = PostgresTable(
+ name="_inbox_usage_reports",
+ postgres_table_name="signals_signalreport",
+ fields={
+ "id": UUIDDatabaseField(name="id"),
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "triggering_signal_id": UUIDDatabaseField(name="triggering_signal_id", nullable=True),
+ },
+)
+
+
+def _scout_usage(team_id: int, receipts: QuerySet[SignalSpend]) -> list[InboxUsageScout]:
+ scout_receipts = receipts.filter(kind=SignalSpend.Kind.SCOUT_RUN)
+ reports_by_scout: dict[tuple[UUID | None, str], set[str]] = {}
+ for config_id, skill, report_ids in (
+ SignalScoutRun.objects.for_team(team_id)
+ .filter(id__in=scout_receipts.values("scout_run_id"))
+ .values_list("scout_config_id", "skill_name", "emitted_report_ids")
+ .iterator(chunk_size=1000)
+ ):
+ reports_by_scout.setdefault((config_id, skill), set()).update(report_ids or [])
+ rows = scout_receipts.values(
+ "scout_run__scout_config_id", "scout_run__skill_name", "scout_run__scout_config__display_name"
+ ).annotate(
+ credits=Sum("spend"),
+ exempt=Sum("spend", filter=Q(billing_exempt=True), default=0),
+ runs=Count("scout_run_id", distinct=True),
+ failed=Count("id", filter=Q(accounting_failed=True)),
+ )
+ return [
+ InboxUsageScout(
+ scout_config_id=str(row["scout_run__scout_config_id"]) if row["scout_run__scout_config_id"] else None,
+ skill_name=row["scout_run__skill_name"] or "unknown",
+ display_name=row["scout_run__scout_config__display_name"]
+ or row["scout_run__skill_name"]
+ or "Unknown scout",
+ total_credits=str(row["credits"]),
+ exempt_credits=str(row["exempt"]),
+ run_count=row["runs"],
+ reports_produced=len(
+ reports_by_scout.get((row["scout_run__scout_config_id"], row["scout_run__skill_name"]), set())
+ ),
+ incomplete=bool(row["failed"]),
+ )
+ for row in rows.order_by("-credits", "scout_run__skill_name", "scout_run__scout_config_id")
+ ]
+
+
+class InboxUsageQueryRunner(AnalyticsQueryRunner[InboxUsageQueryResponse]):
+ query: InboxUsageQuery
+ cached_response: CachedInboxUsageQueryResponse
+
+ def __post_init__(self) -> None:
+ self.ch_user = ClickHouseUser.SIGNALS
+ if self.team.parent_team_id and self.team.parent_team_id != self.team.id:
+ raise QueryError("Run the usage query in the parent project that owns the spend records.")
+
+ def _reads_events_route(self) -> bool:
+ return False
+
+ def validate_query_runner_access(self, user: User) -> bool:
+ return UserAccessControl(user=user, team=self.team).assert_access_level_for_resource("signal_usage", "viewer")
+
+ @cached_property
+ def as_of(self) -> datetime:
+ return timezone.now()
+
+ @cached_property
+ def query_date_range(self) -> QueryDateRange:
+ return QueryDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=IntervalType.DAY,
+ now=self.as_of,
+ timezone_info=ZoneInfo("UTC"),
+ exact_timerange=True,
+ earliest_timestamp_fallback=SIGNAL_USAGE_START,
+ )
+
+ @cached_property
+ def period_start(self) -> datetime:
+ if self.period_end <= SIGNAL_USAGE_START:
+ raise QueryError("Usage is available from October 1, 2026. Choose a later date range.")
+ return max(self.query_date_range.date_from(), SIGNAL_USAGE_START)
+
+ @cached_property
+ def period_end(self) -> datetime:
+ return self.query_date_range.date_to()
+
+ @cached_property
+ def receipts(self) -> QuerySet[SignalSpend]:
+ private_runs = SignalScoutRun.objects.for_team(self.team.id).filter(metadata__has_key="scout_trial")
+ return (
+ SignalSpend.objects.for_team(self.team.id)
+ .filter(kind__isnull=False)
+ .filter(
+ Q(finalized_at__gte=SIGNAL_USAGE_START)
+ | Q(finalized_at__isnull=True, created_at__gte=SIGNAL_USAGE_START)
+ )
+ .exclude(scout_run_id__in=private_runs.values("id"))
+ )
+
+ @cached_property
+ def settled(self) -> QuerySet[SignalSpend]:
+ return self.receipts.filter(
+ finalized_at__gte=self.period_start, finalized_at__lt=min(self.period_end, self.as_of)
+ )
+
+ def _refresh_frequency(self) -> timedelta:
+ return timedelta(minutes=5)
+
+ def cache_target_age(self, last_refresh: datetime | None, lazy: bool = False) -> datetime | None:
+ return last_refresh + self._refresh_frequency() if last_refresh else None
+
+ def _is_stale(self, last_refresh: datetime | None, lazy: bool = False) -> bool:
+ target = self.cache_target_age(last_refresh)
+ return target is None or timezone.now() >= target
+
+ def to_query(self) -> ast.SelectQuery:
+ report_ids = [
+ str(report_id)
+ for report_id in self.settled.exclude(report_id=None).values_list("report_id", flat=True).distinct()
+ ]
+ # Finalization can follow signal creation by months, so bound metadata by referenced IDs rather than its timestamp.
+ signals = parse_select(
+ _deduped_signals_subquery(
+ include_content=False,
+ extra_where="document_id IN (SELECT source_signal_id FROM spend) AND rendering = 'plain'",
+ ),
+ placeholders={"model_name": ast.Constant(value=EMBEDDING_MODEL.value)},
+ )
+ query = parse_select(
+ """
+ WITH spend AS (
+ SELECT coalesce(toString(receipt.signal_id), toString(report.triggering_signal_id)) AS source_signal_id,
+ receipt.kind AS kind, receipt.credits AS credits,
+ receipt.billing_exempt AS exempt, receipt.accounting_failed AS failed
+ FROM (
+ SELECT signal_id, report_id, kind, credits, billing_exempt, accounting_failed
+ FROM system.signal_spend
+ WHERE finalized_at >= {period_start} AND finalized_at < {period_end}
+ AND kind != 'scout_run'
+ ) AS receipt
+ LEFT JOIN (
+ SELECT id, triggering_signal_id FROM _inbox_usage_reports
+ WHERE id IN {report_ids}
+ ) AS report
+ ON receipt.report_id = report.id
+ )
+ SELECT nullIf(JSONExtractString(source.metadata, 'source_product'), '') AS source_product,
+ nullIf(JSONExtractString(source.metadata, 'source_type'), '') AS source_type,
+ sumIf(spend.credits, spend.kind = 'ad-hoc'),
+ sumIf(spend.credits, spend.kind IN ('research', 'repo_selection')),
+ sumIf(spend.credits, spend.kind IN ('reviewer_triggered_implementation', 'scout_triggered_implementation')),
+ sum(spend.credits), sumIf(spend.credits, spend.exempt), countIf(spend.failed) > 0
+ FROM spend
+ LEFT JOIN ({signals}) AS source ON spend.source_signal_id = source.document_id
+ GROUP BY source_product, source_type
+ ORDER BY sum(spend.credits) DESC, source_product, source_type
+ LIMIT 10001
+ """,
+ placeholders={
+ "period_start": ast.Constant(value=self.period_start),
+ "period_end": ast.Constant(value=min(self.period_end, self.as_of)),
+ "signals": signals,
+ "report_ids": ast.Constant(value=report_ids),
+ },
+ )
+
+ assert isinstance(query, ast.SelectQuery) and query.ctes is not None
+ spend = query.ctes["spend"].expr
+ assert isinstance(spend, ast.SelectQuery) and spend.select_from and spend.select_from.next_join
+ report = spend.select_from.next_join.table
+ assert isinstance(report, ast.SelectQuery) and report.select_from
+ report.select_from.table_schema = _SPEND_REPORTS
+ return query
+
+ def _sources(self) -> list[InboxUsageSource]:
+ if not self.settled.exclude(kind=SignalSpend.Kind.SCOUT_RUN).exists():
+ return []
+ context = _signals_query_context(self.team)
+ with tags_context(product=Product.SIGNALS, feature=Feature.QUERY):
+ response = execute_hogql_query(
+ query=self.to_query(),
+ team=self.team,
+ context=context,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ ch_user=ClickHouseUser.SIGNALS,
+ workload=self.workload,
+ query_type="InboxUsageQuery",
+ )
+ if response.hasMore or len(response.results or []) > 10000:
+ raise QueryError("Too many source groups for a usage summary. Use SQL to query a narrower set of sources.")
+ return [
+ InboxUsageSource(
+ source_product=product,
+ source_type=source_type,
+ processing_credits=str(processing),
+ research_credits=str(research),
+ implementation_credits=str(implementation),
+ total_credits=str(total),
+ exempt_credits=str(exempt),
+ incomplete=bool(incomplete),
+ )
+ for product, source_type, processing, research, implementation, total, exempt, incomplete in response.results
+ or []
+ ]
+
+ def _calculate(self) -> InboxUsageQueryResponse:
+ sources = self._sources()
+ scouts = _scout_usage(self.team.id, self.settled)
+ pending = self.receipts.filter(
+ finalized_at__isnull=True,
+ created_at__gte=self.period_start,
+ created_at__lt=min(self.period_end, self.as_of),
+ ).aggregate(credits=Sum("spend", default=0), count=Count("id"))
+ untracked_runs = (
+ SignalScoutRun.objects.for_team(self.team.id)
+ .filter(created_at__gte=self.period_start, created_at__lt=min(self.period_end, self.as_of))
+ .exclude(metadata__has_key="scout_trial")
+ .filter(~Exists(self.receipts.filter(kind=SignalSpend.Kind.SCOUT_RUN, scout_run_id=OuterRef("pk"))))
+ .count()
+ )
+ buckets: list[InboxUsageSource | InboxUsageScout] = [*sources, *scouts]
+ return InboxUsageQueryResponse(
+ results=InboxUsage(
+ project_id=self.team.id,
+ period_start=self.period_start,
+ period_end=self.period_end,
+ as_of=self.as_of,
+ total_credits=str(sum((Decimal(row.total_credits) for row in buckets), Decimal(0))),
+ exempt_credits=str(sum((Decimal(row.exempt_credits) for row in buckets), Decimal(0))),
+ unsettled_credits=str(pending["credits"]),
+ untracked_scout_run_count=untracked_runs,
+ incomplete=bool(pending["count"] or untracked_runs or any(row.incomplete for row in buckets)),
+ attribution_incomplete=any(row.source_product is None or row.source_type is None for row in sources),
+ sources=sources,
+ scouts=scouts,
+ pricing=InboxUsagePricing(usd_per_credit=str(Decimal(1) / SIGNALS_CREDITS_PER_DOLLAR)),
+ ),
+ timings=self.timings.to_list(),
+ )
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index 9277f6cf5825..44277f9b70a5 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -7,7 +7,11 @@ from products.signals.backend.presentation.inbox_summary import InboxSummaryView
from products.signals.backend.presentation.onboarding import InboxOnboardingViewSet
from products.signals.backend.presentation.reviewer_exclusions import SignalReviewerExclusionViewSet
from products.signals.backend.presentation.scout_rubrics import SignalScoutRubricViewSet
-from products.signals.backend.presentation.spend import SignalSourceSpendViewSet, SignalSpendViewSet
+from products.signals.backend.presentation.spend import (
+ SignalMonthlyUsageViewSet,
+ SignalSourceSpendViewSet,
+ SignalSpendViewSet,
+)
from products.signals.backend.scout_chat import SignalScoutChatTaskViewSet
from products.signals.backend.scout_harness.views import (
SignalProjectProfileViewSet,
@@ -24,6 +28,7 @@ from products.signals.backend.views import SignalViewSet
def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"signals/usage", SignalMonthlyUsageViewSet, "project_signals_usage", ["team_id"])
routers.projects.register(r"signals/spend", SignalSpendViewSet, "project_signals_spend", ["team_id"])
routers.projects.register(
r"signals/source_spend", SignalSourceSpendViewSet, "project_signals_source_spend", ["team_id"]
diff --git a/products/signals/backend/test/test_inbox_usage_query_runner.py b/products/signals/backend/test/test_inbox_usage_query_runner.py
new file mode 100644
index 000000000000..957daa19e510
--- /dev/null
+++ b/products/signals/backend/test/test_inbox_usage_query_runner.py
@@ -0,0 +1,237 @@
+import json
+import uuid
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+import time_machine
+from posthog.test.base import ClickhouseTestMixin, NonAtomicAPIBaseTest
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+
+from products.signals.backend.models import SignalReport, SignalSpend
+from products.signals.backend.signal_metadata import EMBEDDING_MODEL
+from products.signals.backend.test.test_scout_harness_api import _make_run
+
+
+class TestInboxUsageQueryRunner(ClickhouseTestMixin, NonAtomicAPIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(team_scope(self.team.pk))
+ self.base = datetime.now(UTC) - timedelta(days=2)
+
+ @time_machine.travel("2026-10-02T12:00:00Z", tick=False)
+ def test_usage_history_starts_in_october_for_summary_and_sql(self) -> None:
+ start = datetime(2026, 10, 1, tzinfo=UTC)
+ before = start - timedelta(seconds=1)
+ visible_ids = set()
+ for created_at, finalized_at, amount, visible in [
+ (before, before, "99", False),
+ (before, None, "99", False),
+ (before, start, "3", True),
+ (start, start + timedelta(seconds=1), "4", True),
+ (start, None, "2", True),
+ ]:
+ run = _make_run(self.team)
+ receipt = SignalSpend.objects.for_team(self.team.pk).create(
+ team=self.team,
+ kind=SignalSpend.Kind.SCOUT_RUN,
+ scout_run=run,
+ task_run_id=run.task_run_id,
+ spend=amount,
+ finalized_at=finalized_at,
+ )
+ SignalSpend.objects.for_team(self.team.pk).filter(id=receipt.id).update(created_at=created_at)
+ if visible:
+ visible_ids.add(str(receipt.id))
+ path = f"/api/projects/{self.team.pk}/query/"
+ summary = self.client.post(
+ path,
+ {"query": {"kind": "InboxUsageQuery", "dateRange": {"date_from": "all", "explicitDate": True}}},
+ format="json",
+ )
+ assert summary.status_code == 200, summary.content
+ usage = summary.json()["results"]
+ assert usage["period_start"] == "2026-10-01T00:00:00Z"
+ assert Decimal(usage["total_credits"]) == Decimal(7)
+ assert Decimal(usage["unsettled_credits"]) == Decimal(2)
+ sql = self.client.post(
+ path,
+ {"query": {"kind": "HogQLQuery", "query": "SELECT id FROM system.signal_spend"}},
+ format="json",
+ )
+ assert sql.status_code == 200, sql.content
+ assert {row[0] for row in sql.json()["results"]} == visible_ids
+ unavailable = self.client.post(
+ path,
+ {
+ "query": {
+ "kind": "InboxUsageQuery",
+ "dateRange": {"date_from": "2026-09-01", "date_to": "2026-10-01", "explicitDate": True},
+ }
+ },
+ format="json",
+ )
+ assert unavailable.status_code == 400, unavailable.content
+
+ def _emit_version(
+ self,
+ *,
+ document_id: str,
+ report_id: str,
+ source_product: str,
+ inserted_at: datetime,
+ spend_metadata: dict | None = None,
+ ) -> None:
+ sync_execute(
+ f"""INSERT INTO distributed_posthog_document_embeddings_{EMBEDDING_MODEL.value.replace("-", "_")}
+ (team_id, product, document_type, rendering, document_id, timestamp, inserted_at, content, metadata, embedding, _timestamp, _offset, _partition)
+ VALUES""",
+ [
+ (
+ self.team.id,
+ "signals",
+ "signal",
+ "plain",
+ document_id,
+ inserted_at,
+ inserted_at,
+ "",
+ json.dumps(
+ {
+ "report_id": report_id,
+ "source_product": source_product,
+ "source_type": "some_type",
+ **(spend_metadata or {}),
+ }
+ ),
+ [0.0] * 1536,
+ inserted_at,
+ 0,
+ 0,
+ )
+ ],
+ team_id=self.team.id,
+ )
+
+ def test_monthly_usage_attributes_implementation_once_and_preserves_unknown_sources(self) -> None:
+ signal_id = uuid.uuid4()
+ research_signal_id = uuid.uuid4()
+ report = SignalReport.objects.create(
+ team=self.team, triggering_signal_id=signal_id, status=SignalReport.Status.DELETED
+ )
+ settled_at = datetime(self.base.year, self.base.month, 1, tzinfo=UTC)
+ self._emit_version(
+ document_id=str(signal_id),
+ report_id=str(report.id),
+ source_product="linear",
+ inserted_at=self.base,
+ spend_metadata={"total_spend": 999},
+ )
+ self._emit_version(
+ document_id=str(signal_id),
+ report_id=str(report.id),
+ source_product="github",
+ inserted_at=self.base + timedelta(hours=1),
+ spend_metadata={"total_spend": 999},
+ )
+ self._emit_version(
+ document_id=str(research_signal_id),
+ report_id=str(report.id),
+ source_product="linear",
+ inserted_at=self.base,
+ )
+ receipts = [
+ SignalSpend(team=self.team, kind=SignalSpend.Kind.AD_HOC, signal_id=signal_id, spend="2.1250"),
+ SignalSpend(
+ team=self.team,
+ kind=SignalSpend.Kind.RESEARCH,
+ signal_id=research_signal_id,
+ task_run_id=uuid.uuid4(),
+ spend="3",
+ ),
+ SignalSpend(
+ team=self.team,
+ kind=SignalSpend.Kind.REVIEWER_TRIGGERED_IMPLEMENTATION,
+ report=report,
+ task_run_id=uuid.uuid4(),
+ spend="5",
+ billing_exempt=True,
+ ),
+ SignalSpend(
+ team=self.team,
+ kind=SignalSpend.Kind.SCOUT_TRIGGERED_IMPLEMENTATION,
+ report=report,
+ task_run_id=uuid.uuid4(),
+ spend="7",
+ ),
+ SignalSpend(
+ team=self.team, kind=SignalSpend.Kind.AD_HOC, signal_id=uuid.uuid4(), spend="11", accounting_failed=True
+ ),
+ ]
+ receipts.extend(
+ SignalSpend(team=self.team, kind=SignalSpend.Kind.AD_HOC, signal_id=uuid.uuid4(), spend="0.0001")
+ for _ in range(1001)
+ )
+ for receipt in receipts:
+ receipt.finalized_at = settled_at
+ SignalSpend.objects.for_team(self.team.id).bulk_create(receipts)
+ SignalSpend.objects.for_team(self.team.id).filter(id__in=[receipt.id for receipt in receipts]).update(
+ created_at=settled_at - timedelta(days=40)
+ )
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ kind=SignalSpend.Kind.AD_HOC,
+ signal_id=uuid.uuid4(),
+ spend=999,
+ finalized_at=settled_at - timedelta(microseconds=1),
+ )
+ other_team = Team.objects.create(organization=self.organization)
+ SignalSpend.objects.for_team(other_team.id).create(
+ team=other_team, kind=SignalSpend.Kind.AD_HOC, signal_id=signal_id, spend=999, finalized_at=settled_at
+ )
+ with self.capture_select_queries() as queries:
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/usage/?month={self.base:%Y-%m}")
+ assert len(queries) == 1
+
+ assert response.status_code == 200, response.content
+ data = response.json()
+ assert data["total_credits"] == "28.2251"
+ assert data["exempt_credits"] == "5.0000"
+ assert data["incomplete"] is True
+ assert data["attribution_incomplete"] is True
+ assert data["sources"] == [
+ {
+ "source_product": "github",
+ "source_type": "some_type",
+ "processing_credits": "2.1250",
+ "research_credits": "0.0000",
+ "implementation_credits": "12.0000",
+ "total_credits": "14.1250",
+ "exempt_credits": "5.0000",
+ "incomplete": False,
+ },
+ {
+ "source_product": None,
+ "source_type": None,
+ "processing_credits": "11.1001",
+ "research_credits": "0.0000",
+ "implementation_credits": "0.0000",
+ "total_credits": "11.1001",
+ "exempt_credits": "0.0000",
+ "incomplete": True,
+ },
+ {
+ "source_product": "linear",
+ "source_type": "some_type",
+ "processing_credits": "0.0000",
+ "research_credits": "3.0000",
+ "implementation_credits": "0.0000",
+ "total_credits": "3.0000",
+ "exempt_credits": "0.0000",
+ "incomplete": False,
+ },
+ ]
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 41f2c50837ff..92a0f6b0ecc1 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -59,6 +59,7 @@ from products.signals.backend.models import (
SignalSpend,
)
from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCH
+from products.signals.backend.presentation.spend import MonthlyUsageQuerySerializer
from products.signals.backend.quota import SelfDrivingQuotaGate
from products.signals.backend.scout_harness.config_registry import register_missing_configs
from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY, stamp_derived_metadata
@@ -6171,11 +6172,19 @@ class TestScoutHarnessLighthouseAPI(APIBaseTest):
assert self._spent(sibling_run) == 0
+class TestMonthlyUsageQuery(SimpleTestCase):
+ @parameterized.expand(["2026-00", "2026-13", "2026-1", "0000-01", "9999-12", "2026-11-01", "2026-09"])
+ def test_invalid_month(self, month: str) -> None:
+ serializer = MonthlyUsageQuerySerializer(data={"month": month})
+ assert not serializer.is_valid()
+ assert "month" in serializer.errors
+
+
class TestScoutSpendOverview(APIBaseTest):
@parameterized.expand(
[
(endpoint, scope, report_status)
- for endpoint in ("scouts", "sources", "report")
+ for endpoint in ("scouts", "sources", "report", "monthly", "monthly_query")
for scope in ("signal_usage", "signal_scout", "task")
for report_status in (
[SignalReport.Status.POTENTIAL, SignalReport.Status.SUPPRESSED]
@@ -6189,6 +6198,8 @@ class TestScoutSpendOverview(APIBaseTest):
path = {
"scouts": "signals/spend/",
"sources": "signals/source_spend/",
+ "monthly": "signals/usage/",
+ "monthly_query": "query/",
"report": f"signals/reports/{report.id}/spend/",
}[endpoint]
raw = generate_random_token_personal()
@@ -6196,15 +6207,199 @@ class TestScoutSpendOverview(APIBaseTest):
label="usage-read",
user=self.user,
secure_value=hash_key_value(raw),
- scopes=[f"{scope}:read"],
+ scopes=[f"{scope}:read", "query:read"] if endpoint == "monthly_query" else [f"{scope}:read"],
scoped_teams=[self.team.id],
)
self.client.logout()
with patch("products.signals.backend.spend_reporting.execute_hogql_query") as query:
query.return_value.results = []
- response = self.client.get(f"/api/projects/{self.team.id}/{path}", HTTP_AUTHORIZATION=f"Bearer {raw}")
+ if endpoint == "monthly_query":
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/{path}",
+ {"query": {"kind": "InboxUsageQuery", "dateRange": {"date_from": "-7d"}}},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {raw}",
+ )
+ else:
+ response = self.client.get(f"/api/projects/{self.team.id}/{path}", HTTP_AUTHORIZATION=f"Bearer {raw}")
assert response.status_code == (200 if scope == "signal_usage" else 403), response.content
+ @time_machine.travel("2026-12-15T12:00:00Z", tick=False)
+ def test_monthly_scout_usage_counts_each_run_once_and_keeps_unsettled_separate(self) -> None:
+ self.client.force_login(self.user)
+ self.team.timezone = "America/Los_Angeles"
+ self.team.save(update_fields=["timezone"])
+ finalized_at = datetime(2026, 12, 1, tzinfo=UTC)
+ report_ids = [str(uuid4()), str(uuid4())]
+ first = _make_run(self.team, emitted_report_ids=report_ids)
+ repeated = _make_run(self.team, emitted_report_ids=report_ids[:1])
+ empty = _make_run(self.team, emitted_report_ids=[])
+ pending = _make_run(self.team)
+ untracked = _make_run(self.team)
+ private = _make_run(self.team, metadata={"scout_trial": {"version": 1}})
+ outside = _make_run(self.team)
+ other_team = Team.objects.create(organization=self.organization)
+ other = _make_run(other_team)
+ for run, amount, completed in [
+ (first, "12.1250", finalized_at),
+ (repeated, "3.0000", finalized_at),
+ (empty, "4.0000", finalized_at),
+ (pending, "1.5000", None),
+ (private, "999.0000", finalized_at),
+ (outside, "999.0000", datetime(2027, 1, 1, tzinfo=UTC)),
+ (other, "999.0000", finalized_at),
+ ]:
+ receipt = SignalSpend.objects.for_team(run.team_id).create(
+ team_id=run.team_id,
+ kind=SignalSpend.Kind.SCOUT_RUN,
+ scout_run=run,
+ task_run_id=run.task_run_id,
+ spend=Decimal(amount),
+ finalized_at=completed,
+ billing_exempt=run == empty,
+ )
+ SignalSpend.objects.for_team(run.team_id).filter(id=receipt.id).update(
+ created_at=datetime(2026, 12, 1, tzinfo=UTC)
+ )
+ SignalScoutRun.objects.for_team(self.team.id).filter(id=untracked.id).update(
+ created_at=datetime(2026, 12, 1, tzinfo=UTC)
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/usage/")
+ assert response.status_code == 200, response.content
+ data = response.json()
+ assert data["period_start"] == "2026-12-01T00:00:00Z"
+ assert data["period_end"] == "2027-01-01T00:00:00Z"
+ assert data["total_credits"] == "19.1250"
+ assert data["exempt_credits"] == "4.0000"
+ assert data["unsettled_credits"] == "1.5000"
+ assert data["untracked_scout_run_count"] == 1
+ assert data["incomplete"] is True
+ assert data["sources"] == []
+ assert data["scouts"] == [
+ {
+ "scout_config_id": str(first.scout_config_id),
+ "skill_name": first.skill_name,
+ "display_name": first.skill_name,
+ "total_credits": "19.1250",
+ "exempt_credits": "4.0000",
+ "run_count": 3,
+ "reports_produced": 2,
+ "incomplete": False,
+ }
+ ]
+ assert Decimal(data["total_credits"]) * Decimal(data["pricing"]["usd_per_credit"]) == Decimal("0.191250")
+ child = Team.objects.create(organization=self.organization, parent_team=self.team)
+ child_response = self.client.get(f"/api/projects/{child.id}/signals/usage/")
+ assert child_response.status_code == 200, child_response.content
+ assert child_response.json()["project_id"] == self.team.id
+ assert child_response.json()["total_credits"] == "19.1250"
+ assert child_response.json()["scouts"] == data["scouts"]
+ query_payload = {
+ "query": {
+ "kind": "InboxUsageQuery",
+ "dateRange": {"date_from": "2026-12-01", "date_to": "2027-01-01", "explicitDate": True},
+ }
+ }
+ query_response = self.client.post(f"/api/projects/{self.team.id}/query/", query_payload, format="json")
+ assert query_response.status_code == 200, query_response.content
+ assert query_response.json()["results"]["total_credits"] == data["total_credits"]
+ assert query_response.json()["is_cached"] is True
+ child_query = self.client.post(f"/api/projects/{child.id}/query/", query_payload, format="json")
+ assert child_query.status_code == 400, child_query.content
+
+ SignalSpend.objects.for_team(self.team.id).filter(scout_run=first).update(spend=Decimal("20.1250"))
+ cached = self.client.get(f"/api/projects/{self.team.id}/signals/usage/").json()
+ assert cached["total_credits"] == data["total_credits"]
+ assert cached["as_of"] == data["as_of"]
+ with time_machine.travel("2026-12-15T12:06:00Z", tick=False):
+ refreshed = self.client.get(f"/api/projects/{self.team.id}/signals/usage/").json()
+ assert refreshed["total_credits"] == "27.1250"
+ with time_machine.travel("2027-01-02T12:00:00Z", tick=False):
+ self.client.force_login(self.user)
+ next_month_response = self.client.get(f"/api/projects/{self.team.id}/signals/usage/")
+ assert next_month_response.status_code == 200, next_month_response.content
+ next_month = next_month_response.json()
+ assert next_month["period_start"] == "2027-01-01T00:00:00Z"
+ assert next_month["total_credits"] == "999.0000"
+
+ @parameterized.expand(
+ [
+ (
+ "exact",
+ {
+ "date_from": "2026-12-15T12:00:00+01:00",
+ "date_to": "2026-12-15T12:30:00+01:00",
+ "explicitDate": True,
+ },
+ "2026-12-15T11:00:00Z",
+ "2026-12-15T11:30:00Z",
+ "2.1250",
+ ),
+ (
+ "exclusive_end",
+ {"date_from": "2026-12-15T10:00:00Z", "date_to": "2026-12-15T11:00:00Z", "explicitDate": True},
+ "2026-12-15T10:00:00Z",
+ "2026-12-15T11:00:00Z",
+ "0",
+ ),
+ (
+ "relative",
+ {"date_from": "-2h", "explicitDate": True},
+ "2026-12-15T10:00:00Z",
+ "2026-12-15T12:00:00Z",
+ "2.1250",
+ ),
+ (
+ "all",
+ {"date_from": "all", "explicitDate": True},
+ "2026-10-01T00:00:00Z",
+ "2026-12-15T12:00:00Z",
+ "2.1250",
+ ),
+ (
+ "clipped_to_available_history",
+ {"date_from": "2026-09-01", "explicitDate": True},
+ "2026-10-01T00:00:00Z",
+ "2026-12-15T12:00:00Z",
+ "2.1250",
+ ),
+ ]
+ )
+ @time_machine.travel("2026-12-15T12:00:00Z", tick=False)
+ def test_usage_query_date_range(
+ self, _name: str, date_range: dict[str, str | bool], start: str, end: str, credits: str
+ ) -> None:
+ self.client.force_login(self.user)
+ self.team.timezone = "America/Los_Angeles"
+ self.team.save(update_fields=["timezone"])
+ run = _make_run(self.team)
+ receipt = SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ kind=SignalSpend.Kind.SCOUT_RUN,
+ scout_run=run,
+ task_run_id=run.task_run_id,
+ spend=Decimal("2.1250"),
+ finalized_at=datetime(2026, 12, 15, 11, tzinfo=UTC),
+ )
+ SignalSpend.objects.for_team(self.team.id).filter(id=receipt.id).update(
+ created_at=datetime(2026, 11, 1, tzinfo=UTC)
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/query/",
+ {"query": {"kind": "InboxUsageQuery", "dateRange": date_range}},
+ format="json",
+ )
+ assert response.status_code == 200, response.content
+ data = response.json()["results"]
+ assert data["period_start"] == start
+ assert data["period_end"] == end
+ assert data["total_credits"] == credits
+
+ @parameterized.expand(["2026-13", "2026-09"])
+ def test_monthly_usage_rejects_invalid_month(self, month: str) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/usage/?month={month}")
+ assert response.status_code == 400
+
@parameterized.expand([False, True])
def test_spend_is_team_scoped_and_excludes_private_and_old_runs(self, child_environment: bool) -> None:
run = _make_run(self.team)
@@ -6258,7 +6453,8 @@ class TestScoutSpendOverview(APIBaseTest):
cached = SpendReporting(self.team).scouts()
assert cached.scout_spend.total_spend == 200.375
- def test_child_scoped_api_key_cannot_read_parent_spend(self) -> None:
+ @parameterized.expand(["spend", "usage"])
+ def test_child_scoped_api_key_cannot_read_parent_spend(self, endpoint: str) -> None:
child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child")
raw = generate_random_token_personal()
PersonalAPIKey.objects.create(
@@ -6270,7 +6466,7 @@ class TestScoutSpendOverview(APIBaseTest):
)
self.client.logout()
- response = self.client.get(f"/api/projects/{child.id}/signals/spend/", HTTP_AUTHORIZATION=f"Bearer {raw}")
+ response = self.client.get(f"/api/projects/{child.id}/signals/{endpoint}/", HTTP_AUTHORIZATION=f"Bearer {raw}")
assert response.status_code == status.HTTP_403_FORBIDDEN
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 0c68a068ebbe..e91d38b7336c 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -10934,6 +10934,122 @@ export interface SpendOverviewApi {
scout_spend: SpendAmountApi
}
+export interface MonthlySourceUsageApi {
+ /**
+ * Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ total_credits: string
+ /**
+ * Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ exempt_credits: string
+ /** Whether accounting is missing, failed, or still settling. */
+ incomplete: boolean
+ /**
+ * Product that emitted the signal. Null means attribution is unavailable; usage is retained.
+ * @nullable
+ */
+ source_product: string | null
+ /**
+ * Signal type within the source product.
+ * @nullable
+ */
+ source_type: string | null
+ /**
+ * Credits for processing this source's signals.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ processing_credits: string
+ /**
+ * Research and repository-selection credits attributed to their triggering signals.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ research_credits: string
+ /**
+ * Implementation credits attributed to each report's current triggering signal.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ implementation_credits: string
+}
+
+export interface MonthlyScoutUsageApi {
+ /**
+ * Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ total_credits: string
+ /**
+ * Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ exempt_credits: string
+ /** Whether accounting is missing, failed, or still settling. */
+ incomplete: boolean
+ /**
+ * Scout configuration UUID, if it still exists.
+ * @nullable
+ */
+ scout_config_id: string | null
+ /** Scout skill name. */
+ skill_name: string
+ /** Scout display name, falling back to its skill name. */
+ display_name: string
+ /** Number of tracked scout runs whose spend finalized in this month, including runs with no reports. */
+ run_count: number
+ /** Distinct report IDs emitted by these runs. Reports can be shared across scouts; do not sum this as a project report count. */
+ reports_produced: number
+}
+
+export interface UsagePricingApi {
+ /** Currency of the recorded usage value: USD. */
+ currency: string
+ /**
+ * Multiply credits by this value to get recorded usage in USD, before billing exemptions, grants, discounts, or invoice rounding.
+ * @pattern ^-?\d{0,4}(?:\.\d{0,8})?$
+ */
+ usd_per_credit: string
+}
+
+export interface MonthlyUsageApi {
+ /**
+ * Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ total_credits: string
+ /**
+ * Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ exempt_credits: string
+ /** Whether accounting is missing, failed, or still settling. */
+ incomplete: boolean
+ /** Canonical project that owns these spend records. A child environment resolves to its parent, which the caller must also be allowed to read. */
+ project_id: number
+ /** Inclusive start of the UTC calendar month. */
+ period_start: string
+ /** Exclusive end of the UTC calendar month. */
+ period_end: string
+ /** Time this summary was computed. The current month is partial. */
+ as_of: string
+ /**
+ * Recorded credits for unfinalized work created in this month, excluded from total_credits. This is not the full outstanding balance from earlier months.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ unsettled_credits: string
+ /** Public scout runs created in this month with no spend record. Their unknown costs are not counted as zero. */
+ untracked_scout_run_count: number
+ /** Whether any source attribution is missing. Unattributed credits remain in sources and total_credits. */
+ attribution_incomplete: boolean
+ /** Signal processing, research, and implementation grouped by source. Excludes scout execution costs. */
+ sources: MonthlySourceUsageApi[]
+ /** Scout execution costs, excluding downstream report work, which appears in sources. The sources and scouts totals sum to total_credits. */
+ scouts: MonthlyScoutUsageApi[]
+ /** Server-provided denomination for converting recorded credits to USD. This summary is not an invoice. */
+ pricing: UsagePricingApi
+}
+
export interface SignalUserAutonomyConfigApi {
readonly id: string
readonly user: _UserApi
@@ -11927,3 +12043,12 @@ export type SignalsSourceConfigsListParams = {
*/
offset?: number
}
+
+export type SignalsMonthlyUsageParams = {
+ /**
+ * UTC calendar month in YYYY-MM format, from 2026-10 onward. Defaults to the current month. Usage is grouped by finalization time.
+ * @minLength 1
+ * @pattern ^[0-9]{4}-(0[1-9]|1[0-2])$
+ */
+ month?: string
+}
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index ff2af6688706..2b31212379dd 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -31,6 +31,7 @@ import type {
InboxSummaryApi,
LighthouseAuditRequestApi,
LighthouseAuditResponseApi,
+ MonthlyUsageApi,
PaginatedPauseStateResponseListApi,
PaginatedSignalReportArtefactListApi,
PaginatedSignalReportCheckListApi,
@@ -148,6 +149,7 @@ import type {
SignalsActivitySummaryVersionsRetrieveParams,
SignalsAnomaliesInsightRetrieveParams,
SignalsAnomaliesSearchRetrieveParams,
+ SignalsMonthlyUsageParams,
SignalsProcessingListParams,
SignalsReportArtefactsListParams,
SignalsReportChecksListParams,
@@ -3414,6 +3416,33 @@ export const signalsSpendOverview = async (projectId: string, options?: RequestI
})
}
+export const getSignalsMonthlyUsageUrl = (projectId: string, params?: SignalsMonthlyUsageParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/usage/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/usage/`
+}
+
+export const signalsMonthlyUsage = async (
+ projectId: string,
+ params?: SignalsMonthlyUsageParams,
+ options?: RequestInit
+): Promise<MonthlyUsageApi> => {
+ return apiMutator<MonthlyUsageApi>(getSignalsMonthlyUsageUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getUsersSignalAutonomyRetrieveUrl = (userId: string) => {
return `/api/users/${userId}/signal_autonomy/`
}
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 905cdbd0c2af..fdb38f01ce55 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -885,6 +885,26 @@ tools:
- research_instructions
- implementation_instructions
- scout_instructions
+ inbox-usage-get:
+ operation: signals_monthly_usage
+ enabled: true
+ title: Get monthly Self-driving usage
+ description: >
+ Get recorded Self-driving usage for the selected project's UTC calendar month, defaulting to this month.
+ Usage is available from October 2026 onward. Returns credits by signal source (processing, research, and
+ downstream report implementation) and by scout (execution costs, including runs that produce no report). The
+ two breakdowns are additive: their totals sum to total_credits. Implementation uses the report's current
+ triggering source. Missing source metadata stays in a null-source bucket. Finalized costs belong to the
+ month they finalized, even if work started earlier. Unsettled work created in the month is reported
+ separately, as are missing scout receipts. Fractional credits are decimal strings; multiply by
+ pricing.usd_per_credit to convert to USD. Exempt credits are a subset of recorded usage. This is not an
+ invoice: billing cutovers, grants, discounts and rounding can change billed amounts. Child environments
+ resolve to the parent project, which requires parent-project access; project_id identifies the project whose
+ usage is returned. For daily trends, individual runs or reports, custom filters, or finer breakdowns, use
+ execute-sql with system.signal_spend, system.scout_runs and system.inbox_reports. Report detail can show
+ associated scout costs shared with other reports; do not add those shared amounts to this summary or across
+ reports.
+ feature_flag: self-driving-usage-display
scout-check-record-result:
operation: signals_scout_record_check_result
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 306a18810ed1..73762a3dad37 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8379,6 +8379,22 @@
"readOnlyHint": false
}
},
+ "inbox-usage-get": {
+ "description": "Get recorded Self-driving usage for the selected project's UTC calendar month, defaulting to this month. Usage is available from October 2026 onward. Returns credits by signal source (processing, research, and downstream report implementation) and by scout (execution costs, including runs that produce no report). The two breakdowns are additive: their totals sum to total_credits. Implementation uses the report's current triggering source. Missing source metadata stays in a null-source bucket. Finalized costs belong to the month they finalized, even if work started earlier. Unsettled work created in the month is reported separately, as are missing scout receipts. Fractional credits are decimal strings; multiply by pricing.usd_per_credit to convert to USD. Exempt credits are a subset of recorded usage. This is not an invoice: billing cutovers, grants, discounts and rounding can change billed amounts. Child environments resolve to the parent project, which requires parent-project access; project_id identifies the project whose usage is returned. For daily trends, individual runs or reports, custom filters, or finer breakdowns, use execute-sql with system.signal_spend, system.scout_runs and system.inbox_reports. Report detail can show associated scout costs shared with other reports; do not add those shared amounts to this summary or across reports.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Get monthly Self-driving usage",
+ "title": "Get monthly Self-driving usage",
+ "required_scopes": ["signal_usage:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/usage/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "self-driving-usage-display"
+ },
"insight-create": {
"description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics chart, `DataVisualizationNode` for a SQL visualization, and `DataTableNode` with an `EventsQuery` source for a table of individual events:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\nBare `TrendsQuery`, `HogQLQuery`, and `EventsQuery` definitions are accepted too. They are wrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nA saved SQL insight must follow the dashboard and insight date range. Before you save a `HogQLQuery`, replace its fixed date window, such as `timestamp >= now() - INTERVAL 30 DAY`, with the `{filters}` placeholder: `WHERE event = 'signed_up' AND {filters}`. Then put the requested window in `query.source.filters.dateRange`, for example `{\"date_from\": \"-30d\"}`. A fixed window ignores the date picker, and `{filters}` without a `dateRange` shows all time. `{filters}` also applies the property and test-account filters. For a table without a `timestamp` column, bind its date column with `{filters(created_at AS timestamp)}`.\n\nSave a `MetricsQuery` or `MetricsHistogramQuery` bare, as the top-level `query`. Do not put it in an `InsightVizNode`.\n\nFor a PromQL metrics insight, set `language` to `promql`, put the expression in `promql`, and send `clauses` as an empty list. When query-metrics accepts a `promql` field, test the expression with it first:\n\n```json\n{ \"name\": \"Request rate\", \"query\": { \"kind\": \"MetricsQuery\", \"language\": \"promql\", \"promql\": \"sum(rate(http_requests_total[5m]))\", \"clauses\": [], \"dateRange\": { \"date_from\": \"-24h\" } } }\n```\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.",
"category": "Product analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 2d416494045e..be26806ff93a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8611,6 +8611,22 @@
"readOnlyHint": false
}
},
+ "inbox-usage-get": {
+ "description": "Get recorded Self-driving usage for the selected project's UTC calendar month, defaulting to this month. Usage is available from October 2026 onward. Returns credits by signal source (processing, research, and downstream report implementation) and by scout (execution costs, including runs that produce no report). The two breakdowns are additive: their totals sum to total_credits. Implementation uses the report's current triggering source. Missing source metadata stays in a null-source bucket. Finalized costs belong to the month they finalized, even if work started earlier. Unsettled work created in the month is reported separately, as are missing scout receipts. Fractional credits are decimal strings; multiply by pricing.usd_per_credit to convert to USD. Exempt credits are a subset of recorded usage. This is not an invoice: billing cutovers, grants, discounts and rounding can change billed amounts. Child environments resolve to the parent project, which requires parent-project access; project_id identifies the project whose usage is returned. For daily trends, individual runs or reports, custom filters, or finer breakdowns, use execute-sql with system.signal_spend, system.scout_runs and system.inbox_reports. Report detail can show associated scout costs shared with other reports; do not add those shared amounts to this summary or across reports.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Get monthly Self-driving usage",
+ "title": "Get monthly Self-driving usage",
+ "required_scopes": ["signal_usage:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/usage/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "self-driving-usage-display"
+ },
"insight-create": {
"description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics chart, `DataVisualizationNode` for a SQL visualization, and `DataTableNode` with an `EventsQuery` source for a table of individual events:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\nBare `TrendsQuery`, `HogQLQuery`, and `EventsQuery` definitions are accepted too. They are wrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nA saved SQL insight must follow the dashboard and insight date range. Before you save a `HogQLQuery`, replace its fixed date window, such as `timestamp >= now() - INTERVAL 30 DAY`, with the `{filters}` placeholder: `WHERE event = 'signed_up' AND {filters}`. Then put the requested window in `query.source.filters.dateRange`, for example `{\"date_from\": \"-30d\"}`. A fixed window ignores the date picker, and `{filters}` without a `dateRange` shows all time. `{filters}` also applies the property and test-account filters. For a table without a `timestamp` column, bind its date column with `{filters(created_at AS timestamp)}`.\n\nSave a `MetricsQuery` or `MetricsHistogramQuery` bare, as the top-level `query`. Do not put it in an `InsightVizNode`.\n\nFor a PromQL metrics insight, set `language` to `promql`, put the expression in `promql`, and send `clauses` as an empty list. When query-metrics accepts a `promql` field, test the expression with it first:\n\n```json\n{ \"name\": \"Request rate\", \"query\": { \"kind\": \"MetricsQuery\", \"language\": \"promql\", \"promql\": \"sum(rate(http_requests_total[5m]))\", \"clauses\": [], \"dateRange\": { \"date_from\": \"-24h\" } } }\n```\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.",
"category": "Product analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ac7a80e92254..9e1d20ca9067 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -56246,6 +56246,95 @@ export namespace Schemas {
version?: number | null;
}
+ export interface InboxUsagePricing {
+ currency?: 'USD';
+ /** Multiply credits by this value for recorded USD usage, before billing adjustments. */
+ usd_per_credit: string;
+ }
+
+ export interface InboxUsageScout {
+ display_name: string;
+ /** Billing-exempt subset of total_credits. */
+ exempt_credits: string;
+ incomplete: boolean;
+ /** Distinct reports emitted by this scout; reports may be shared across scouts. */
+ reports_produced: number;
+ run_count: number;
+ scout_config_id?: string | null;
+ skill_name: string;
+ /** Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits. */
+ total_credits: string;
+ }
+
+ export interface InboxUsageSource {
+ /** Billing-exempt subset of total_credits. */
+ exempt_credits: string;
+ implementation_credits: string;
+ incomplete: boolean;
+ processing_credits: string;
+ research_credits: string;
+ source_product?: string | null;
+ source_type?: string | null;
+ /** Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits. */
+ total_credits: string;
+ }
+
+ export interface InboxUsage {
+ as_of: string;
+ /** Missing source metadata is retained in a null-source bucket. */
+ attribution_incomplete: boolean;
+ /** Billing-exempt subset of total_credits. */
+ exempt_credits: string;
+ incomplete: boolean;
+ period_end: string;
+ period_start: string;
+ pricing: InboxUsagePricing;
+ project_id: number;
+ /** Scout execution only. These totals and source totals sum to total_credits. */
+ scouts: InboxUsageScout[];
+ /** Processing, research and implementation. Excludes scout execution. */
+ sources: InboxUsageSource[];
+ /** Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits. */
+ total_credits: string;
+ /** Unfinalized credits created in the selected range, excluded from total_credits. */
+ unsettled_credits: string;
+ untracked_scout_run_count: number;
+ }
+
+ export interface InboxUsageQueryResponse {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: InboxUsage;
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface InboxUsageQuery {
+ /** UTC date range. Use explicitDate for exact bounds; the end is exclusive. */
+ dateRange: DateRange;
+ kind?: 'InboxUsageQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ response?: InboxUsageQueryResponse | null;
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export type UsageMetricDisplay = typeof UsageMetricDisplay[keyof typeof UsageMetricDisplay];
@@ -57301,7 +57390,7 @@ export namespace Schemas {
query: string;
response?: HogQLMetadataResponse | null;
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | InboxUsageQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -57327,7 +57416,7 @@ export namespace Schemas {
query: string;
response?: HogQLAutocompleteResponse | null;
/** Query in whose context to validate. */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | InboxUsageQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -67438,6 +67527,122 @@ export namespace Schemas {
created_time: string | null;
}
+ export interface MonthlyScoutUsage {
+ /**
+ * Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ total_credits: string;
+ /**
+ * Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ exempt_credits: string;
+ /** Whether accounting is missing, failed, or still settling. */
+ incomplete: boolean;
+ /**
+ * Scout configuration UUID, if it still exists.
+ * @nullable
+ */
+ scout_config_id: string | null;
+ /** Scout skill name. */
+ skill_name: string;
+ /** Scout display name, falling back to its skill name. */
+ display_name: string;
+ /** Number of tracked scout runs whose spend finalized in this month, including runs with no reports. */
+ run_count: number;
+ /** Distinct report IDs emitted by these runs. Reports can be shared across scouts; do not sum this as a project report count. */
+ reports_produced: number;
+ }
+
+ export interface MonthlySourceUsage {
+ /**
+ * Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ total_credits: string;
+ /**
+ * Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ exempt_credits: string;
+ /** Whether accounting is missing, failed, or still settling. */
+ incomplete: boolean;
+ /**
+ * Product that emitted the signal. Null means attribution is unavailable; usage is retained.
+ * @nullable
+ */
+ source_product: string | null;
+ /**
+ * Signal type within the source product.
+ * @nullable
+ */
+ source_type: string | null;
+ /**
+ * Credits for processing this source's signals.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ processing_credits: string;
+ /**
+ * Research and repository-selection credits attributed to their triggering signals.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ research_credits: string;
+ /**
+ * Implementation credits attributed to each report's current triggering signal.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ implementation_credits: string;
+ }
+
+ export interface UsagePricing {
+ /** Currency of the recorded usage value: USD. */
+ currency: string;
+ /**
+ * Multiply credits by this value to get recorded usage in USD, before billing exemptions, grants, discounts, or invoice rounding.
+ * @pattern ^-?\d{0,4}(?:\.\d{0,8})?$
+ */
+ usd_per_credit: string;
+ }
+
+ export interface MonthlyUsage {
+ /**
+ * Recorded finalized usage in credits, including exempt usage. Decimal string preserving fractional credits.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ total_credits: string;
+ /**
+ * Subset of total_credits marked billing-exempt; not an invoice adjustment or grant balance.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ exempt_credits: string;
+ /** Whether accounting is missing, failed, or still settling. */
+ incomplete: boolean;
+ /** Canonical project that owns these spend records. A child environment resolves to its parent, which the caller must also be allowed to read. */
+ project_id: number;
+ /** Inclusive start of the UTC calendar month. */
+ period_start: string;
+ /** Exclusive end of the UTC calendar month. */
+ period_end: string;
+ /** Time this summary was computed. The current month is partial. */
+ as_of: string;
+ /**
+ * Recorded credits for unfinalized work created in this month, excluded from total_credits. This is not the full outstanding balance from earlier months.
+ * @pattern ^-?\d{0,20}(?:\.\d{0,4})?$
+ */
+ unsettled_credits: string;
+ /** Public scout runs created in this month with no spend record. Their unknown costs are not counted as zero. */
+ untracked_scout_run_count: number;
+ /** Whether any source attribution is missing. Unattributed credits remain in sources and total_credits. */
+ attribution_incomplete: boolean;
+ /** Signal processing, research, and implementation grouped by source. Excludes scout execution costs. */
+ sources: MonthlySourceUsage[];
+ /** Scout execution costs, excluding downstream report work, which appears in sources. The sources and scouts totals sum to total_credits. */
+ scouts: MonthlyScoutUsage[];
+ /** Server-provided denomination for converting recorded credits to USD. This summary is not an invoice. */
+ pricing: UsagePricing;
+ }
+
export interface MoveTileTile {
/** Dashboard tile ID to move. */
id: number;
@@ -95192,7 +95397,7 @@ export namespace Schemas {
* ```
*
* For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | InboxUsageQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
/** Whether results should be calculated sync or async, and how much to rely on the cache:
* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
@@ -97351,7 +97556,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: UsageMetric[];
+ results: InboxUsage;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -97361,6 +97566,28 @@ export namespace Schemas {
}
export interface QueryResponseAlternative89 {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: UsageMetric[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface QueryResponseAlternative90 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -97390,7 +97617,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -97421,7 +97648,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative91 {
+ export interface QueryResponseAlternative92 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97443,7 +97670,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative92 {
+ export interface QueryResponseAlternative93 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -97470,9 +97697,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative93ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative94ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97485,7 +97712,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative93ResultsItem[];
+ results: QueryResponseAlternative94ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -97494,7 +97721,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative94 {
+ export interface QueryResponseAlternative95 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97516,7 +97743,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative95 {
+ export interface QueryResponseAlternative96 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97538,7 +97765,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative96 {
+ export interface QueryResponseAlternative97 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97560,7 +97787,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative97 {
+ export interface QueryResponseAlternative98 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Whether another page of individual model identifiers is available. */
@@ -97584,7 +97811,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative98 {
+ export interface QueryResponseAlternative99 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97606,7 +97833,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative99 {
+ export interface QueryResponseAlternative100 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97628,7 +97855,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative100 {
+ export interface QueryResponseAlternative101 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97650,7 +97877,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative101 {
+ export interface QueryResponseAlternative102 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97672,7 +97899,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative102 {
+ export interface QueryResponseAlternative103 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97695,7 +97922,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative103 {
+ export interface QueryResponseAlternative104 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97717,7 +97944,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative104 {
+ export interface QueryResponseAlternative105 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97745,7 +97972,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative105 {
+ export interface QueryResponseAlternative106 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97767,7 +97994,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative106 {
+ export interface QueryResponseAlternative107 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97789,7 +98016,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative107 {
+ export interface QueryResponseAlternative108 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97811,7 +98038,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative108 {
+ export interface QueryResponseAlternative109 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97833,7 +98060,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative109 {
+ export interface QueryResponseAlternative110 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97855,7 +98082,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative110 {
+ export interface QueryResponseAlternative111 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97877,7 +98104,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative111 {
+ export interface QueryResponseAlternative112 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97899,7 +98126,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative112 {
+ export interface QueryResponseAlternative113 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Whether more reports exist past this page. */
@@ -97923,7 +98150,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative113 {
+ export interface QueryResponseAlternative114 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -97945,7 +98172,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | unknown | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112 | QueryResponseAlternative113;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | unknown | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112 | QueryResponseAlternative113 | QueryResponseAlternative114;
export interface QueryScanResponse {
analysis?: QueryScanAnalysis | null;
@@ -97956,11 +98183,11 @@ export namespace Schemas {
}
export interface QueryUpgradeRequest {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | InboxUsageQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
}
export interface QueryUpgradeResponse {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingReleasesQuery | ErrorTrackingIssueCorrelationQuery | ErrorTrackingIssueEventsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebAgentAnalyticsQuery | WebPageDirectoryQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | MarketingAnalyticsRetentionQuery | MarketingAnalyticsSearchQuery | MarketingAnalyticsRecommendationsQuery | DataVisualizationNode | BIVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | MetricsHistogramQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | InboxUsageQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPModelBreakdownQuery | MCPProtocolVersionBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | MCPMissingCapabilitiesQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {
@@ -134096,6 +134323,15 @@ export namespace Schemas {
offset?: number;
};
+ export type SignalsMonthlyUsageParams = {
+ /**
+ * UTC calendar month in YYYY-MM format, from 2026-10 onward. Defaults to the current month. Usage is grouped by finalization time.
+ * @minLength 1
+ * @pattern ^[0-9]{4}-(0[1-9]|1[0-2])$
+ */
+ month?: string;
+ };
+
export type SlackAppWorkspaceSetupRetrieveParams = {
/**
* Where the Slack install started. slack_page adds the steps for a person who sets up Slack on purpose.
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 9f0127e2984d..0cce230ad599 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 83 enabled ops
+ * PostHog API - MCP 84 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -5651,3 +5651,24 @@ export const SignalsSourceConfigsPartialUpdateBody = () => zod.object({
'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
),
})
+
+export const SignalsMonthlyUsageParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const signalsMonthlyUsageQueryMonthRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$')
+
+export const SignalsMonthlyUsageQueryParams = () => zod.object({
+ month: zod
+ .string()
+ .min(1)
+ .regex(signalsMonthlyUsageQueryMonthRegExp)
+ .optional()
+ .describe(
+ 'UTC calendar month in YYYY-MM format, from 2026-10 onward. Defaults to the current month. Usage is grouped by finalization time.'
+ ),
+})
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index d8f8b462c227..af63d8c355f8 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -1421,6 +1421,27 @@ const inboxSteeringInstructionsUpdate = (): ToolBase<
},
})
+const InboxUsageGetSchema = () => {
+ const SignalsMonthlyUsageQueryParams = orvalSchemas.SignalsMonthlyUsageQueryParams()
+ return SignalsMonthlyUsageQueryParams
+}
+
+const inboxUsageGet = (): ToolBase<ReturnType<typeof InboxUsageGetSchema>, Schemas.MonthlyUsage> => ({
+ name: 'inbox-usage-get',
+ schema: InboxUsageGetSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof InboxUsageGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.MonthlyUsage>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/usage/`,
+ query: {
+ month: params.month,
+ },
+ })
+ return result
+ },
+})
+
const ScoutCheckRecordResultSchema = () => {
const SignalsScoutRecordCheckResultBody = orvalSchemas.SignalsScoutRecordCheckResultBody()
const SignalsScoutRecordCheckResultParams = orvalSchemas.SignalsScoutRecordCheckResultParams()
@@ -3805,6 +3826,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'inbox-source-configs-update': inboxSourceConfigsUpdate,
'inbox-steering-instructions-get': inboxSteeringInstructionsGet,
'inbox-steering-instructions-update': inboxSteeringInstructionsUpdate,
+ 'inbox-usage-get': inboxUsageGet,
'scout-check-record-result': scoutCheckRecordResult,
'scout-config-create': scoutConfigCreate,
'scout-config-delete': scoutConfigDelete,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-usage-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-usage-get.json
new file mode 100644
index 000000000000..0822f8b4423d
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-usage-get.json
@@ -0,0 +1,12 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "month": {
+ "description": "UTC calendar month in YYYY-MM format, from 2026-10 onward. Defaults to the current month. Usage is grouped by finalization time.",
+ "minLength": 1,
+ "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])$",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 31942bffc65b..3cc661c9f0b9 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1197,11 +1197,13 @@ describe('Tool Filtering - Feature Flags', () => {
'subscription-source-summaries',
'workflows-mcp-onboarding',
'aeo-citation-tracking',
+ 'self-driving-usage-display',
])
)
expect(flags).toContain('ai-observability-offline-evaluations')
expect(allFlags).not.toContain('dashboard-widgets')
- expect(flags).toHaveLength(36)
+ expect(allFlags).not.toContain('self-driving-usage-mcp')
+ expect(flags).toHaveLength(37)
})
it('keeps human and task context wiki tools on separate scopes', () => {
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index 41091f621b69..cae0a14a347c 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -90,6 +90,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {
// visual-review, etc.) stay off to keep the surface stable.
// agent-feedback is always_available and no longer flag-gated, so it appears regardless.
const featureFlags = {
+ 'self-driving-usage-display': true,
tracing: true,
'logs-agent-tools': true,
tasks: true,