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(usage): add real-time usage project filters (#92315)

Ben White39038afcbac5
diff --git a/docs/internal/usage-record-producers.md b/docs/internal/usage-record-producers.md
index 443c2fb0e4ad..ec8c6461faef 100644
--- a/docs/internal/usage-record-producers.md
+++ b/docs/internal/usage-record-producers.md
@@ -226,6 +226,11 @@ SELECT producer_id, usage_key, sum(quantity), count()
FROM billing_usage_records GROUP BY 1, 2 ORDER BY 1, 2
```
+Local development exposes `billing_usage_records` for every organization. Set
+`BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS` to a comma-separated list of organization UUIDs in other deployments.
+Configure that environment variable before enabling the real-time usage feature flag. The table stays hidden for every
+other organization.
+
## What is not reported yet
All current collectors mirror usage into usage-ingestion. Existing billing still reads the nightly usage report.
diff --git a/frontend/src/scenes/real-time-usage/RealTimeUsage.tsx b/frontend/src/scenes/real-time-usage/RealTimeUsage.tsx
index 5386a1b0c2d6..82d0815b19f2 100644
--- a/frontend/src/scenes/real-time-usage/RealTimeUsage.tsx
+++ b/frontend/src/scenes/real-time-usage/RealTimeUsage.tsx
@@ -1,11 +1,13 @@
import { useActions, useValues } from 'kea'
import { IconRefresh } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSkeleton } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'
import { AppMetricsTimeSeriesChart } from 'lib/components/AppMetrics/AppMetricsTimeSeriesChart'
import { NotFound } from 'lib/components/NotFound'
import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { humanFriendlyNumber } from 'lib/utils/numbers'
@@ -51,8 +53,19 @@ export function RealTimeUsage(): JSX.Element {
}
function RealTimeUsageBody(): JSX.Element {
- const { usageData, usageDataError, usageDataLoading, usageGranularity, usageRange } = useValues(realTimeUsageLogic)
+ const {
+ breakdownByProject,
+ hasMultipleProjects,
+ projectOptions,
+ selectedProjectIds,
+ usageData,
+ usageDataError,
+ usageDataLoading,
+ usageGranularity,
+ usageRange,
+ } = useValues(realTimeUsageLogic)
const { loadUsageData, setUsageFilters } = useActions(realTimeUsageLogic)
+ const projectCount = selectedProjectIds.length || projectOptions.length
return (
<SceneContent>
@@ -62,29 +75,94 @@ function RealTimeUsageBody(): JSX.Element {
resourceType={{ type: 'billing' }}
/>
+ <LemonBanner type="warning" className="mt-4">
+ Experimental: This page is under construction. Do not rely on this data yet.
+ </LemonBanner>
+
<div className="mt-6 max-w-300 space-y-4">
- <div className="flex flex-wrap items-center gap-2">
- <LemonSegmentedButton
- value={usageRange}
- onChange={(value) =>
- setUsageFilters({ range: value as UsageRange, granularity: usageGranularity })
- }
- options={RANGE_OPTIONS}
- size="small"
- />
- <LemonSegmentedButton
- value={usageGranularity}
- onChange={(value) =>
- setUsageFilters({ range: usageRange, granularity: value as UsageGranularity })
- }
- options={GRANULARITY_OPTIONS.map((option) => ({
- ...option,
- disabledReason: isGranularityAvailable(option.value, usageRange)
- ? undefined
- : 'Only available for the last 24 hours',
- }))}
- size="small"
- />
+ <div className="flex flex-wrap items-end gap-4">
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Time range</LemonLabel>
+ <LemonSegmentedButton
+ value={usageRange}
+ onChange={(value) =>
+ setUsageFilters({
+ range: value as UsageRange,
+ granularity: usageGranularity,
+ projectIds: selectedProjectIds,
+ breakdownByProject,
+ })
+ }
+ options={RANGE_OPTIONS}
+ size="small"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Granularity</LemonLabel>
+ <LemonSegmentedButton
+ value={usageGranularity}
+ onChange={(value) =>
+ setUsageFilters({
+ range: usageRange,
+ granularity: value as UsageGranularity,
+ projectIds: selectedProjectIds,
+ breakdownByProject,
+ })
+ }
+ options={GRANULARITY_OPTIONS.map((option) => ({
+ ...option,
+ disabledReason: isGranularityAvailable(option.value, usageRange)
+ ? undefined
+ : 'Only available for the last 24 hours',
+ }))}
+ size="small"
+ />
+ </div>
+ {hasMultipleProjects && (
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Projects</LemonLabel>
+ <LemonInputSelect
+ mode="multiple"
+ displayMode="count"
+ bulkActions="select-and-clear-all"
+ className="min-w-50"
+ value={selectedProjectIds.map(String)}
+ onChange={(values) =>
+ setUsageFilters({
+ range: usageRange,
+ granularity: usageGranularity,
+ projectIds: values.map(Number).filter(Number.isInteger),
+ breakdownByProject,
+ })
+ }
+ placeholder="All projects"
+ options={projectOptions}
+ allowCustomValues={false}
+ data-attr="real-time-usage-project-filter"
+ />
+ </div>
+ )}
+ {hasMultipleProjects && (
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Break down by</LemonLabel>
+ <LemonSelect
+ value={breakdownByProject}
+ onChange={(value) =>
+ setUsageFilters({
+ range: usageRange,
+ granularity: usageGranularity,
+ projectIds: selectedProjectIds,
+ breakdownByProject: value,
+ })
+ }
+ options={[
+ { value: false, label: 'Organization-wide' },
+ { value: true, label: 'Project' },
+ ]}
+ data-attr="real-time-usage-project-breakdown"
+ />
+ </div>
+ )}
<LemonButton
className="ml-auto"
icon={<IconRefresh />}
@@ -109,14 +187,25 @@ function RealTimeUsageBody(): JSX.Element {
<section>
<h2 className="mb-1 text-lg font-semibold">Usage over time</h2>
<p className="mb-3 text-sm text-secondary">
- Each line represents one product area, usage type, and unit.
+ Each line represents one {breakdownByProject ? 'project, ' : ''}product area, usage
+ type, and unit.
</p>
- <div className="h-100 rounded border bg-surface-primary p-2">
- {usageDataLoading || !usageData ? (
+ <div className="relative h-100 rounded border bg-surface-primary p-2">
+ {!usageData ? (
<LemonSkeleton className="size-full" />
) : (
<AppMetricsTimeSeriesChart timeSeries={usageData.timeSeries} showLegend />
)}
+ {usageDataLoading && projectCount > 0 && (
+ <div
+ className="absolute inset-0 flex items-center justify-center bg-surface-primary/80"
+ aria-live="polite"
+ >
+ <span className="rounded border bg-surface-primary px-3 py-2 text-sm text-secondary shadow-sm">
+ Loading usage for {projectCount} project{projectCount === 1 ? '' : 's'}…
+ </span>
+ </div>
+ )}
</div>
</section>
@@ -127,6 +216,9 @@ function RealTimeUsageBody(): JSX.Element {
loading={usageDataLoading || !usageData}
loadingSkeletonRows={5}
columns={[
+ ...(breakdownByProject
+ ? [{ title: 'Project', key: 'projectName', dataIndex: 'projectName' as const }]
+ : []),
{ title: 'Product area', key: 'producerId', dataIndex: 'producerId' },
{ title: 'Usage type', key: 'usageKey', dataIndex: 'usageKey' },
{ title: 'Unit', key: 'unit', dataIndex: 'unit' },
diff --git a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts
new file mode 100644
index 000000000000..eea0663368e0
--- /dev/null
+++ b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts
@@ -0,0 +1,63 @@
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { HogQLQueryResponse } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { filtersFromParams, parseUsageData, realTimeUsageLogic } from './realTimeUsageLogic'
+
+const response = (results: unknown[][]): HogQLQueryResponse => ({ results }) as HogQLQueryResponse
+
+describe('real-time usage logic', () => {
+ it('reads project filters and breakdowns from the URL', () => {
+ expect(filtersFromParams({ project_ids: '2,4', breakdown_by_project: true })).toMatchObject({
+ projectIds: [2, 4],
+ breakdownByProject: true,
+ })
+ expect(filtersFromParams({ project_ids: '' }).projectIds).toEqual([])
+ })
+
+ it('drops project filters that are not in the organization', () => {
+ initKeaTests(true, MOCK_DEFAULT_TEAM, MOCK_DEFAULT_PROJECT, { ...MOCK_DEFAULT_ORGANIZATION, teams: [] })
+ const logic = realTimeUsageLogic()
+ logic.mount()
+
+ logic.actions.setUsageFilters({
+ range: '1d',
+ granularity: 'hour',
+ projectIds: [999],
+ breakdownByProject: false,
+ })
+
+ expect(logic.values.selectedProjectIds).toEqual([])
+ })
+
+ it('keeps projects separate when the project breakdown is enabled', () => {
+ const bucket = Math.floor(Date.now() / 1000 / 3600) * 3600
+ const usageData = parseUsageData(
+ [
+ {
+ project: { id: 1, name: 'First project' },
+ rows: response([['ingestion', 'events', 'events', 2]]),
+ timeSeries: response([[bucket, 'ingestion: events (events)', 2]]),
+ },
+ {
+ project: { id: 2, name: 'Second project' },
+ rows: response([['ingestion', 'events', 'events', 3]]),
+ timeSeries: response([[bucket, 'ingestion: events (events)', 3]]),
+ },
+ ],
+ '1d',
+ 'hour',
+ true
+ )
+
+ expect(usageData.rows).toEqual([
+ { projectName: 'Second project', producerId: 'ingestion', usageKey: 'events', unit: 'events', quantity: 3 },
+ { projectName: 'First project', producerId: 'ingestion', usageKey: 'events', unit: 'events', quantity: 2 },
+ ])
+ expect(usageData.timeSeries.series.map((series) => series.name)).toEqual([
+ 'First project: ingestion: events (events)',
+ 'Second project: ingestion: events (events)',
+ ])
+ })
+})
diff --git a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts
index b2667969e14c..70399d87b519 100644
--- a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts
+++ b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
@@ -8,19 +8,32 @@ import { dayjs } from 'lib/dayjs'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
+import { ConcurrencyController } from '~/lib/utils/concurrencyController'
import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
import { OrganizationType } from '~/types'
export type UsageGranularity = '5m' | 'hour' | 'day'
export type UsageRange = '1d' | '7d' | '30d'
-export type RealTimeUsageRow = { producerId: string; usageKey: string; unit: string; quantity: number }
+export type RealTimeUsageRow = {
+ projectName?: string
+ producerId: string
+ usageKey: string
+ unit: string
+ quantity: number
+}
type RealTimeUsageData = {
rows: RealTimeUsageRow[]
timeSeries: AppMetricsTimeSeriesResponse
}
+type ProjectUsageData = {
+ project: { id: number; name: string }
+ rows: HogQLQueryResponse
+ timeSeries: HogQLQueryResponse
+}
+
const RANGE_INTERVALS: Record<UsageRange, string> = {
'1d': '24 HOUR',
'7d': '7 DAY',
@@ -33,6 +46,8 @@ const RANGE_SECONDS: Record<UsageRange, number> = {
'30d': 30 * 24 * 60 * 60,
}
+const PROJECT_QUERY_CONCURRENCY = 5
+
// Buckets are cut by integer arithmetic on the Unix timestamp rather than by dateTrunc, so a bucket
// is the same absolute instant for every project and for the browser. dateTrunc cuts on the team's
// timezone, and the chart merges several projects into one axis, so its boundaries disagreed both
@@ -48,7 +63,12 @@ export function isGranularityAvailable(granularity: UsageGranularity, range: Usa
return granularity !== '5m' || range === '1d'
}
-export type UsageFilters = { range: UsageRange; granularity: UsageGranularity }
+export type UsageFilters = {
+ range: UsageRange
+ granularity: UsageGranularity
+ projectIds: number[]
+ breakdownByProject: boolean
+}
// A shared or reloaded URL can carry anything, so fall back rather than query on a bad value.
export function filtersFromParams(searchParams: Record<string, any>): UsageFilters {
@@ -60,7 +80,15 @@ export function filtersFromParams(searchParams: Record<string, any>): UsageFilte
searchParams.granularity === '5m' || searchParams.granularity === 'day' || searchParams.granularity === 'hour'
? searchParams.granularity
: 'hour'
- return { range, granularity }
+ // pinned: URL parameter names — bookmarks rely on them.
+ const projectIds = String(searchParams.project_ids ?? '')
+ .split(',')
+ .filter(Boolean)
+ .map(Number)
+ .filter(Number.isInteger)
+ const breakdownByProject =
+ searchParams.breakdown_by_project === true || searchParams.breakdown_by_project === 'true'
+ return { range, granularity, projectIds, breakdownByProject }
}
// Bucket starts as Unix seconds, matching what the query returns.
@@ -99,19 +127,21 @@ async function queryUsage(teamId: number, query: string): Promise<HogQLQueryResp
})
}
-function parseUsageData(
- responses: { rows: HogQLQueryResponse; timeSeries: HogQLQueryResponse }[],
+export function parseUsageData(
+ responses: ProjectUsageData[],
range: UsageRange,
- granularity: UsageGranularity
+ granularity: UsageGranularity,
+ breakdownByProject: boolean
): RealTimeUsageData {
const rows = new Map<string, RealTimeUsageRow>()
const series = new Map<string, Map<number, number>>()
for (const response of responses) {
for (const [producerId, usageKey, unit, quantity] of response.rows.results ?? []) {
- const key = `${producerId}:${usageKey}:${unit}`
+ const key = `${breakdownByProject ? `${response.project.id}:` : ''}${producerId}:${usageKey}:${unit}`
const current = rows.get(key)
rows.set(key, {
+ projectName: breakdownByProject ? response.project.name : undefined,
producerId: String(producerId),
usageKey: String(usageKey),
unit: String(unit),
@@ -121,9 +151,12 @@ function parseUsageData(
for (const [bucket, seriesName, quantity] of response.timeSeries.results ?? []) {
const bucketStart = Number(bucket)
- const values = series.get(String(seriesName)) ?? new Map<number, number>()
+ const key = breakdownByProject
+ ? `${response.project.id}:${response.project.name}: ${seriesName}`
+ : String(seriesName)
+ const values = series.get(key) ?? new Map<number, number>()
values.set(bucketStart, (values.get(bucketStart) ?? 0) + Number(quantity))
- series.set(String(seriesName), values)
+ series.set(key, values)
}
}
@@ -135,8 +168,8 @@ function parseUsageData(
timeSeries: {
// Buckets are UTC-aligned, so label them in UTC rather than in the reader's timezone.
labels: starts.map((start) => dayjs.unix(start).utc().format('YYYY-MM-DD HH:mm')),
- series: Array.from(series.entries()).map(([name, values]) => ({
- name,
+ series: Array.from(series.entries()).map(([key, values]) => ({
+ name: breakdownByProject ? key.replace(/^\d+:/, '') : key,
values: starts.map((start) => values.get(start) ?? 0),
})),
},
@@ -150,6 +183,10 @@ export interface realTimeUsageLogicValues {
usageDataLoading: boolean
usageGranularity: UsageGranularity
usageRange: UsageRange
+ selectedProjectIds: number[]
+ breakdownByProject: boolean
+ projectOptions: { key: string; label: string }[]
+ hasMultipleProjects: boolean
}
export interface realTimeUsageLogicActions {
loadUsageData: () => { value: true }
@@ -168,15 +205,24 @@ export type realTimeUsageLogicType = MakeLogicType<realTimeUsageLogicValues, rea
export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
path(['scenes', 'real-time-usage', 'realTimeUsageLogic']),
connect(() => ({ values: [organizationLogic, ['currentOrganization']] })),
- actions({
+ actions(({ values }) => ({
// Normalized here so every caller, including a hand-edited URL, lands on a valid pair.
- setUsageFilters: (filters: UsageFilters) => ({
- filters: {
- ...filters,
- granularity: isGranularityAvailable(filters.granularity, filters.range) ? filters.granularity : 'hour',
- },
- }),
- }),
+ setUsageFilters: (filters: UsageFilters) => {
+ const teams = values.currentOrganization?.teams
+
+ return {
+ filters: {
+ ...filters,
+ granularity: isGranularityAvailable(filters.granularity, filters.range)
+ ? filters.granularity
+ : 'hour',
+ projectIds: teams
+ ? filters.projectIds.filter((projectId) => teams.some((team) => team.id === projectId))
+ : filters.projectIds,
+ },
+ }
+ },
+ })),
loaders(({ values }) => ({
usageData: [
null as RealTimeUsageData | null,
@@ -185,22 +231,36 @@ export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
const rowsQuery = usageQuery(values.usageRange, values.usageGranularity, false)
const timeSeriesQuery = usageQuery(values.usageRange, values.usageGranularity, true)
const teams = values.currentOrganization?.teams ?? []
- // Only allowlisted projects resolve billing_usage_records, and the allowlist is
+ const selectedTeams = values.selectedProjectIds.length
+ ? teams.filter((team) => values.selectedProjectIds.includes(team.id))
+ : teams
+ // Only allowlisted organizations resolve billing_usage_records, and the allowlist is
// server-side, so a project that cannot read it is skipped rather than failing
// the whole organization's chart.
+ const projectQueryConcurrency = new ConcurrencyController(PROJECT_QUERY_CONCURRENCY)
const settled = await Promise.allSettled(
- teams.map(async (team) => ({
- rows: await queryUsage(team.id, rowsQuery),
- timeSeries: await queryUsage(team.id, timeSeriesQuery),
- }))
+ selectedTeams.map((team) =>
+ projectQueryConcurrency.run({
+ fn: async () => ({
+ project: { id: team.id, name: team.name },
+ rows: await queryUsage(team.id, rowsQuery),
+ timeSeries: await queryUsage(team.id, timeSeriesQuery),
+ }),
+ })
+ )
)
const responses = settled
.filter((result) => result.status === 'fulfilled')
.map((result) => result.value)
- if (!responses.length && teams.length) {
+ if (!responses.length && selectedTeams.length) {
throw settled[0].status === 'rejected' ? settled[0].reason : new Error('No usage data')
}
- return parseUsageData(responses, values.usageRange, values.usageGranularity)
+ return parseUsageData(
+ responses,
+ values.usageRange,
+ values.usageGranularity,
+ values.breakdownByProject
+ )
},
},
],
@@ -215,6 +275,18 @@ export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
],
usageGranularity: ['hour' as UsageGranularity, { setUsageFilters: (_, { filters }) => filters.granularity }],
usageRange: ['1d' as UsageRange, { setUsageFilters: (_, { filters }) => filters.range }],
+ selectedProjectIds: [[], { setUsageFilters: (_, { filters }) => filters.projectIds }],
+ breakdownByProject: [false, { setUsageFilters: (_, { filters }) => filters.breakdownByProject }],
+ }),
+ selectors({
+ projectOptions: [
+ (s) => [s.currentOrganization],
+ (currentOrganization: OrganizationType | null): { key: string; label: string }[] =>
+ [...(currentOrganization?.teams ?? [])]
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((team) => ({ key: String(team.id), label: team.name })),
+ ],
+ hasMultipleProjects: [(s) => [s.projectOptions], (projectOptions): boolean => projectOptions.length > 1],
}),
listeners(({ actions }) => ({
setUsageFilters: () => actions.loadUsageData(),
@@ -222,7 +294,12 @@ export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
actionToUrl(({ values }) => ({
setUsageFilters: () => [
router.values.location.pathname,
- { range: values.usageRange, granularity: values.usageGranularity },
+ {
+ range: values.usageRange,
+ granularity: values.usageGranularity,
+ project_ids: values.selectedProjectIds.length ? values.selectedProjectIds.join(',') : undefined,
+ breakdown_by_project: values.breakdownByProject ? 'true' : undefined,
+ },
router.values.hashParams,
{ replace: true },
],
@@ -230,7 +307,12 @@ export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
urlToAction(({ actions, values }) => ({
[urls.organizationBillingRealTimeUsage()]: (_, searchParams) => {
const filters = filtersFromParams(searchParams)
- if (filters.range !== values.usageRange || filters.granularity !== values.usageGranularity) {
+ if (
+ filters.range !== values.usageRange ||
+ filters.granularity !== values.usageGranularity ||
+ filters.breakdownByProject !== values.breakdownByProject ||
+ filters.projectIds.join(',') !== values.selectedProjectIds.join(',')
+ ) {
actions.setUsageFilters(filters)
}
},
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 3f39014e2313..60cc097d5bae 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1721,7 +1721,8 @@ class Database(BaseModel):
is_managed_viewset_enabled=is_managed_viewset_enabled,
is_hogql_warehouse_access_control_enabled=is_hogql_warehouse_access_control_enabled,
is_data_quality_enabled=data_quality_enabled,
- is_billing_usage_records_enabled=team.pk in settings.BILLING_USAGE_RECORDS_HOGQL_TEAM_IDS,
+ is_billing_usage_records_enabled="*" in settings.BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS
+ or team.organization_id in settings.BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS,
# Managed warehouse is a built-in project datastore and has no warehouse-object ACL surface.
# Principals that skip warehouse access control by design:
# - synthetic users (project-wide service tokens, bypass object-level RBAC)
diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.py
index aa93a2a6ba01..9d4ac0d61804 100644
--- a/posthog/hogql/database/schema/test/test_information_schema.py
+++ b/posthog/hogql/database/schema/test/test_information_schema.py
@@ -22,7 +22,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.query import execute_hogql_query
-from posthog.models import Team
+from posthog.models import Organization, Team
from posthog.models.scoping import team_scope
from products.data_modeling.backend.facade.models import (
@@ -265,23 +265,32 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
}
assert {"trace_id", "span_id"}.issubset(columns)
- def test_billing_usage_records_is_listed_only_for_allowlisted_teams(self):
+ def test_billing_usage_records_is_listed_only_for_allowlisted_organizations(self):
# The table has no per-product access scope, so the allowlist is the only thing keeping it
- # out of every other project's catalog.
- def listed_tables() -> set[str]:
+ # out of every other organization's catalog.
+ def listed_tables(team: Team) -> set[str]:
return {
row[0]
for row in execute_hogql_query(
- "SELECT table_name FROM system.information_schema.tables", team=self.team
+ "SELECT table_name FROM system.information_schema.tables", team=team
).results
or []
}
- with override_settings(BILLING_USAGE_RECORDS_HOGQL_TEAM_IDS=set()):
- assert "posthog.billing_usage_records" not in listed_tables()
+ same_organization_team = Team.objects.create(organization=self.organization, name="same organization")
+ other_organization = Organization.objects.create(name="other organization")
+ other_organization_team = Team.objects.create(organization=other_organization, name="other organization")
- with override_settings(BILLING_USAGE_RECORDS_HOGQL_TEAM_IDS={self.team.pk}):
- assert "posthog.billing_usage_records" in listed_tables()
+ with override_settings(BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS=set()):
+ assert "posthog.billing_usage_records" not in listed_tables(self.team)
+
+ with override_settings(BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS={self.organization.id}):
+ assert "posthog.billing_usage_records" in listed_tables(self.team)
+ assert "posthog.billing_usage_records" in listed_tables(same_organization_team)
+ assert "posthog.billing_usage_records" not in listed_tables(other_organization_team)
+
+ with override_settings(BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS={"*"}):
+ assert "posthog.billing_usage_records" in listed_tables(other_organization_team)
usage_columns = {
row[0]
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index 16e876205f81..14168963f796 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -1,6 +1,8 @@
import os
+from typing import Literal
+from uuid import UUID
-from posthog.settings.base_variables import CLOUD_DEPLOYMENT, TEST
+from posthog.settings.base_variables import DEBUG, TEST
from posthog.settings.utils import get_from_env, get_list, get_set
from posthog.utils import str_to_bool
@@ -136,17 +138,16 @@ ELEMENT_CHAIN_AS_STRING_EXCLUDED_TEAMS = get_set(os.getenv("ELEMENT_CHAIN_AS_STR
DROP_EVENTS_BY_TOKEN_DISTINCT_ID = get_from_env("DROP_EVENTS_BY_TOKEN_DISTINCT_ID", None, type_cast=str, optional=True)
-# Projects that see `posthog.billing_usage_records` in HogQL. The table carries usage for every
-# producer in the project and has no per-product access scope, so it stays off the catalog until a
-# project is named here.
+# Organizations that see `posthog.billing_usage_records` in HogQL. The table carries usage for
+# every producer in a project, so this organization-level rollout lets the real-time usage page
+# query all of an organization's projects without exposing the table elsewhere.
#
-# The 1,2 default only applies on PostHog Cloud, where those ids are our own US and EU projects. On a
-# self-hosted deployment they are whichever projects the operator created first, so defaulting there
-# would hand a customer's own members a pre-release table nobody opted into. Empty under TEST too:
-# test teams get sequential ids, so a default would make the catalog depend on which team a test
-# happened to create — tests opt in with override_settings.
-_BILLING_USAGE_RECORDS_DEFAULT_TEAM_IDS = "1,2" if CLOUD_DEPLOYMENT and not TEST else ""
-BILLING_USAGE_RECORDS_HOGQL_TEAM_IDS: set[int] = {
- int(team_id)
- for team_id in get_set(os.getenv("BILLING_USAGE_RECORDS_HOGQL_TEAM_IDS", _BILLING_USAGE_RECORDS_DEFAULT_TEAM_IDS))
+# Local development enables the table for all organizations. Cloud and self-hosted deployments need explicit UUIDs.
+_BILLING_USAGE_RECORDS_DEFAULT_ORGANIZATION_IDS = "*" if DEBUG and not TEST else ""
+BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS: set[UUID | Literal["*"]] = {
+ "*" if organization_id == "*" else UUID(organization_id)
+ for organization_id in get_set(
+ os.getenv("BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS", _BILLING_USAGE_RECORDS_DEFAULT_ORGANIZATION_IDS)
+ )
+ if organization_id
}