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(logs): refactor drop rules page and add preview (#59424)

Frank Hamand931d9ca1d541
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsx
index 4dbecbdf04a6..e1f5a58c13da 100644
--- a/frontend/src/lib/components/Sparkline.tsx
+++ b/frontend/src/lib/components/Sparkline.tsx
@@ -1,9 +1,10 @@
+import annotationPlugin from 'chartjs-plugin-annotation'
import clsx from 'clsx'
import { useMemo, useRef, useState } from 'react'
import { Popover } from '@posthog/lemon-ui'
-import { ScaleOptions, TooltipModel } from 'lib/Chart'
+import { Chart, ScaleOptions, TooltipModel } from 'lib/Chart'
import { getColorVar } from 'lib/colors'
import { useChart } from 'lib/hooks/useChart'
import { useEventListener } from 'lib/hooks/useEventListener'
@@ -13,6 +14,21 @@ import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { LemonSkeleton } from '../lemon-ui/LemonSkeleton'
+// Register once at module load. Chart.register is idempotent so re-registers (eg. by
+// AlertHistoryChart, which also uses the annotation plugin) are safe.
+Chart.register(annotationPlugin)
+
+export interface SparklineReferenceLine {
+ /** Y-axis value the dashed line is drawn at, in the same units as the series data. */
+ value: number
+ /** Color name from `vars.scss` (e.g. 'danger'). @default 'danger' */
+ color?: string
+ /** Optional label to anchor at the end of the line (shown only when provided). */
+ label?: string
+ /** Where to anchor the optional label. @default 'end' */
+ labelPosition?: 'start' | 'center' | 'end'
+}
+
export interface SparklineTimeSeries {
name: string
values: number[]
@@ -54,6 +70,10 @@ export interface SparklineProps {
hideZerosInTooltip?: boolean
/** Sort tooltip items by count (descending). @default false */
sortTooltipByCount?: boolean
+ /** Optional horizontal dashed reference lines (thresholds, goals, limits). */
+ referenceLines?: SparklineReferenceLine[]
+ /** Format the per-series tooltip value. Defaults to `humanFriendlyNumber`. */
+ renderTooltipValue?: (value: number) => string
}
export function Sparkline({
@@ -74,6 +94,8 @@ export function Sparkline({
tooltipRowCutoff,
hideZerosInTooltip = false,
sortTooltipByCount = false,
+ referenceLines,
+ renderTooltipValue,
}: SparklineProps): JSX.Element {
const tooltipRef = useRef<HTMLDivElement | null>(null)
@@ -137,12 +159,19 @@ export function Sparkline({
alignToPixels: true,
}
+ // Make sure reference lines always fit on the chart — Chart.js would otherwise
+ // auto-scale to the data only and a threshold above the peak would be clipped.
+ const referenceLineMax =
+ referenceLines && referenceLines.length > 0 ? Math.max(...referenceLines.map((l) => l.value)) : 0
+
const defaultYScale: AnyScaleOptions = {
// We use the Y axis for the maximum indicator
display: maximumIndicator,
bounds: 'data',
min: 0, // Always starting at 0
- suggestedMax: 1,
+ // Headroom above whichever is taller — data or a reference line — so a threshold
+ // sitting near the chart top still has room for its label without clipping.
+ suggestedMax: referenceLineMax > 0 ? referenceLineMax * 1.2 : 1,
stacked: true,
ticks: {
includeBounds: true,
@@ -213,6 +242,43 @@ export function Sparkline({
setTooltip({ ...tooltip } as TooltipModel<'bar'>)
},
},
+ ...(referenceLines && referenceLines.length > 0
+ ? {
+ annotation: {
+ annotations: Object.fromEntries(
+ referenceLines.map((line, i) => {
+ const lineColor = getColorVar(line.color || 'danger')
+ return [
+ `referenceLine${i}`,
+ {
+ type: 'line',
+ yMin: line.value,
+ yMax: line.value,
+ borderColor: lineColor,
+ borderWidth: 1.5,
+ borderDash: [5, 4],
+ ...(line.label
+ ? {
+ label: {
+ display: true,
+ content: line.label,
+ position: line.labelPosition || 'end',
+ font: { size: 9 },
+ color: lineColor,
+ backgroundColor: 'transparent',
+ // Sit the label just above the line so it doesn't render on top of it.
+ // The 20% y-axis headroom set above guarantees it stays inside the chart.
+ yAdjust: -8,
+ },
+ }
+ : {}),
+ },
+ ]
+ })
+ ),
+ },
+ }
+ : {}),
},
maintainAspectRatio: false,
interaction: {
@@ -223,7 +289,7 @@ export function Sparkline({
},
}
},
- deps: [labels, adjustedData, withXScale, withYScale, renderLabel, data, maximumIndicator, type],
+ deps: [labels, adjustedData, withXScale, withYScale, renderLabel, data, maximumIndicator, type, referenceLines],
})
const dataPointCount = adjustedData[0]?.values?.length || 0
@@ -347,7 +413,7 @@ export function Sparkline({
.filter((item) => !hideZerosInTooltip || item.count > 0)
.sort((a, b) => (sortTooltipByCount ? b.count - a.count : a.order - b.order))}
renderSeries={(value) => value}
- renderCount={(count) => humanFriendlyNumber(count)}
+ renderCount={(count) => (renderTooltipValue ?? humanFriendlyNumber)(count)}
rowCutoff={tooltipRowCutoff}
/>
}
diff --git a/nodejs/src/logs-ingestion/sampling/compile-rules.ts b/nodejs/src/logs-ingestion/sampling/compile-rules.ts
index 2ecb3fdf8f28..3c801d825741 100644
--- a/nodejs/src/logs-ingestion/sampling/compile-rules.ts
+++ b/nodejs/src/logs-ingestion/sampling/compile-rules.ts
@@ -58,7 +58,7 @@ function parseSeverityActions(raw: unknown): [SeverityAction, SeverityAction, Se
}
const MAX_LOGS_PER_SECOND = 1_000_000
-const MAX_BURST_LOGS = 60_000_000
+const MAX_BURST_LOGS = 10_000_000
function parseRateLimitFromConfig(
config: Record<string, unknown>
diff --git a/posthog/clickhouse/logs/logs32.py b/posthog/clickhouse/logs/logs32.py
index 15e8c573995e..6266f36d0424 100644
--- a/posthog/clickhouse/logs/logs32.py
+++ b/posthog/clickhouse/logs/logs32.py
@@ -44,12 +44,12 @@ CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NA
-- temporary columns for materialized views, these expire immediately after initially created but
-- are around for materialized views which pull off from this table
- `_partition` UInt32 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_topic` String TTL created_at + interval 1 second,
- `_offset` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_bytes_uncompressed` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
+ `_partition` UInt32 CODEC(DoubleDelta, ZSTD(1)),
+ `_topic` String,
+ `_offset` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_bytes_uncompressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)),
INDEX idx_severity_text_set severity_text TYPE set(10) GRANULARITY 1,
INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index d2b373f92f42..32bd5d7d019a 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -2659,12 +2659,12 @@
-- temporary columns for materialized views, these expire immediately after initially created but
-- are around for materialized views which pull off from this table
- `_partition` UInt32 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_topic` String TTL created_at + interval 1 second,
- `_offset` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_bytes_uncompressed` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
+ `_partition` UInt32 CODEC(DoubleDelta, ZSTD(1)),
+ `_topic` String,
+ `_offset` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_bytes_uncompressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)),
INDEX idx_severity_text_set severity_text TYPE set(10) GRANULARITY 1,
INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,
@@ -7579,12 +7579,12 @@
-- temporary columns for materialized views, these expire immediately after initially created but
-- are around for materialized views which pull off from this table
- `_partition` UInt32 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_topic` String TTL created_at + interval 1 second,
- `_offset` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_bytes_uncompressed` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
- `_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)) TTL created_at + interval 1 second,
+ `_partition` UInt32 CODEC(DoubleDelta, ZSTD(1)),
+ `_topic` String,
+ `_offset` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_bytes_uncompressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),
+ `_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)),
INDEX idx_severity_text_set severity_text TYPE set(10) GRANULARITY 1,
INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,
diff --git a/posthog/hogql/database/schema/logs.py b/posthog/hogql/database/schema/logs.py
index a1571188861f..6d92df7b74fe 100644
--- a/posthog/hogql/database/schema/logs.py
+++ b/posthog/hogql/database/schema/logs.py
@@ -39,6 +39,7 @@ class LogsTable(Table):
# internal fields for query optimization
"_part_starting_offset": IntegerDatabaseField(name="_part_starting_offset", nullable=True, hidden=True),
"_part_offset": IntegerDatabaseField(name="_part_offset", nullable=True, hidden=True),
+ "_bytes_uncompressed": IntegerDatabaseField(name="_bytes_uncompressed", nullable=True, hidden=True),
"mat_body_ipv4_matches": StringJSONDatabaseField(name="mat_body_ipv4_matches", nullable=True, hidden=True),
}
diff --git a/products/logs/backend/api.py b/products/logs/backend/api.py
index 9f071fca3842..5e924caf4be5 100644
--- a/products/logs/backend/api.py
+++ b/products/logs/backend/api.py
@@ -481,6 +481,10 @@ class _LogsSparklineBucketSerializer(serializers.Serializer):
help_text='Service name when sparklineBreakdownBy="service". Present only for service-broken-down sparklines.',
)
count = serializers.IntegerField()
+ bytes_uncompressed = serializers.IntegerField(
+ required=False,
+ help_text="Sum of uncompressed bytes for the bucket.",
+ )
class _LogsSparklineResponseSerializer(serializers.Serializer):
diff --git a/products/logs/backend/sampling_api.py b/products/logs/backend/sampling_api.py
index 3206c6e8e838..2f31150259fb 100644
--- a/products/logs/backend/sampling_api.py
+++ b/products/logs/backend/sampling_api.py
@@ -86,14 +86,14 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):
)
rule_type = serializers.ChoiceField(
choices=LogsExclusionRule.RuleType.choices,
- help_text="Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).",
+ help_text="Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).",
)
scope_service = serializers.CharField(
required=False,
allow_null=True,
allow_blank=False,
max_length=512,
- help_text="If set, the rule applies only to this service name; null means all services.",
+ help_text="Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.",
)
scope_path_pattern = serializers.CharField(
required=False,
@@ -116,9 +116,8 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):
'Filter group example: `{"type":"AND","values":[{"type":"AND","values":['
'{"key":"service.name","operator":"exact","value":"api"}]}]}`. '
"For severity_sampling: object with `actions` per severity level and optional `always_keep`. "
- "For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` "
- "(integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching "
- "`service.name` on each log line."
+ "For rate_limit: object with required `logs_per_second` (integer KB/s, 1–1000000 = 1 GB/s) and optional `burst_logs` "
+ "(integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to."
)
)
version = serializers.IntegerField(
@@ -167,61 +166,20 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):
mak = config.get("match_attribute_key")
if mak is not None and mak != "" and not isinstance(mak, str):
raise ValidationError({"config": {"match_attribute_key": "Must be a string when provided."}})
- filter_group = config.get("filter_group")
- if filter_group is not None:
- # Validate shape against PropertyGroupFilter so malformed payloads
- # (e.g. a list where an object is expected) are rejected at write
- # time rather than letting them flow through to the ingestion worker.
- # Mirrors the pattern used for alert filters in alerts_api.py.
- try:
- PropertyGroupFilter.model_validate(filter_group)
- except PydanticValidationError as e:
- raise ValidationError(
- {"config": {"filter_group": f"Invalid filter_group shape: {e.errors()[0]['msg']}"}}
- )
- # Bound nesting depth — the Node ingestion worker recurses per
- # record over this tree, so an adversarially deep group is a
- # stack-overflow + CPU footgun on every log line. Matches
- # `MAX_FILTER_GROUP_DEPTH` in
- # `nodejs/src/logs-ingestion/sampling/filter-group-match.ts`.
- if _filter_group_depth(filter_group) > MAX_FILTER_GROUP_DEPTH:
- raise ValidationError(
- {
- "config": {
- "filter_group": f"filter_group is nested too deeply (max depth {MAX_FILTER_GROUP_DEPTH})."
- }
- }
- )
- # Bound total node count — depth alone doesn't bound work per
- # record. A single AND with thousands of sibling leaves is the
- # more realistic abuse vector: it passes the depth check but
- # costs O(leaves) on every log line through the ingestion
- # worker. Matches `MAX_FILTER_GROUP_NODES` in `compile-rules.ts`.
- if _filter_group_node_count(filter_group) > MAX_FILTER_GROUP_NODES:
- raise ValidationError(
- {
- "config": {
- "filter_group": f"filter_group has too many nodes (max {MAX_FILTER_GROUP_NODES} groups + leaves)."
- }
- }
- )
+ self._validate_filter_group(config.get("filter_group"))
if rule_type == LogsExclusionRule.RuleType.RATE_LIMIT:
if not isinstance(config, dict):
raise ValidationError({"config": "rate_limit rules require config to be a JSON object."})
- scope_service = attrs.get("scope_service")
- if scope_service is None and self.instance is not None:
- scope_service = self.instance.scope_service
- if not scope_service or not str(scope_service).strip():
- raise ValidationError(
- {"scope_service": "rate_limit rules require a non-empty service name (service.name on logs)."}
- )
+ self._validate_filter_group(config.get("filter_group"))
lps = config.get("logs_per_second")
if isinstance(lps, bool) or not isinstance(lps, int):
raise ValidationError(
{"config": {"logs_per_second": "Must be an integer (logs per second sustained)."}}
)
if lps < 1 or lps > 1_000_000:
- raise ValidationError({"config": {"logs_per_second": "Must be between 1 and 1000000 inclusive."}})
+ raise ValidationError(
+ {"config": {"logs_per_second": "Must be between 1 KB/s and 1000000 KB/s (1 GB/s) inclusive."}}
+ )
burst = config.get("burst_logs", None)
if burst is not None:
if isinstance(burst, bool) or not isinstance(burst, int):
@@ -230,10 +188,44 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):
raise ValidationError(
{"config": {"burst_logs": "Must be greater than or equal to logs_per_second."}}
)
- if burst > 60_000_000:
- raise ValidationError({"config": {"burst_logs": "Must be at most 60000000."}})
+ if burst > 10_000_000:
+ raise ValidationError({"config": {"burst_logs": "Must be at most 10000000 KB."}})
return attrs
+ def _validate_filter_group(self, filter_group: Any) -> None:
+ if filter_group is None:
+ return
+ # Validate shape against PropertyGroupFilter so malformed payloads
+ # (e.g. a list where an object is expected) are rejected at write
+ # time rather than letting them flow through to the ingestion worker.
+ # Mirrors the pattern used for alert filters in alerts_api.py.
+ try:
+ PropertyGroupFilter.model_validate(filter_group)
+ except PydanticValidationError as e:
+ raise ValidationError({"config": {"filter_group": f"Invalid filter_group shape: {e.errors()[0]['msg']}"}})
+ # Bound nesting depth — the Node ingestion worker recurses per
+ # record over this tree, so an adversarially deep group is a
+ # stack-overflow + CPU footgun on every log line. Matches
+ # `MAX_FILTER_GROUP_DEPTH` in
+ # `nodejs/src/logs-ingestion/sampling/filter-group-match.ts`.
+ if _filter_group_depth(filter_group) > MAX_FILTER_GROUP_DEPTH:
+ raise ValidationError(
+ {"config": {"filter_group": f"filter_group is nested too deeply (max depth {MAX_FILTER_GROUP_DEPTH})."}}
+ )
+ # Bound total node count — depth alone doesn't bound work per
+ # record. A single AND with thousands of sibling leaves is the
+ # more realistic abuse vector: it passes the depth check but
+ # costs O(leaves) on every log line through the ingestion
+ # worker. Matches `MAX_FILTER_GROUP_NODES` in `compile-rules.ts`.
+ if _filter_group_node_count(filter_group) > MAX_FILTER_GROUP_NODES:
+ raise ValidationError(
+ {
+ "config": {
+ "filter_group": f"filter_group has too many nodes (max {MAX_FILTER_GROUP_NODES} groups + leaves)."
+ }
+ }
+ )
+
def validate_scope_attribute_filters(self, value: Any) -> Any:
if not isinstance(value, list):
raise ValidationError("scope_attribute_filters must be a list.")
diff --git a/products/logs/backend/sparkline_query_runner.py b/products/logs/backend/sparkline_query_runner.py
index 18e98dccb64a..e80ca461cbd0 100644
--- a/products/logs/backend/sparkline_query_runner.py
+++ b/products/logs/backend/sparkline_query_runner.py
@@ -40,6 +40,7 @@ class SparklineQueryRunner(LogsQueryRunner):
"time": result[0],
result_key: breakdown_value,
"count": result[2],
+ "bytes_uncompressed": result[3],
}
)
@@ -51,7 +52,8 @@ class SparklineQueryRunner(LogsQueryRunner):
SELECT
am.time_bucket AS time,
{breakdown_field},
- ifNull(ac.event_count, 0) AS count
+ ifNull(ac.event_count, 0) AS count,
+ ifNull(ac.bytes_uncompressed, 0) AS bytes_uncompressed
FROM (
SELECT
dateAdd({date_from_start_of_interval}, {number_interval_period}) AS time_bucket
@@ -73,7 +75,8 @@ class SparklineQueryRunner(LogsQueryRunner):
SELECT
toStartOfInterval({time_field}, {one_interval_period}) AS time,
{breakdown_field},
- count() AS event_count
+ count() AS event_count,
+ sum(_bytes_uncompressed) AS bytes_uncompressed
FROM logs
WHERE {where} AND time >= {date_from_start_of_interval} AND time <= {date_to}
GROUP BY {breakdown_field}, time
diff --git a/products/logs/backend/test/test_sampling_rules_api.py b/products/logs/backend/test/test_sampling_rules_api.py
index f51b275c3f5f..d8b3c90d7f57 100644
--- a/products/logs/backend/test/test_sampling_rules_api.py
+++ b/products/logs/backend/test/test_sampling_rules_api.py
@@ -66,7 +66,9 @@ class TestLogsSamplingRulesAPI(APIBaseTest):
assert ordered[1]["id"] == a["id"]
assert ordered[1]["priority"] == 1
- def test_create_rate_limit_requires_scope_service(self):
+ def test_create_rate_limit_without_scope_service(self):
+ # scope_service is no longer required for rate_limit — the matching
+ # happens through config.filter_group instead.
response = self.client.post(
self.base_url,
self._payload(
@@ -77,8 +79,8 @@ class TestLogsSamplingRulesAPI(APIBaseTest):
),
format="json",
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
- assert response.json()["attr"] == "scope_service"
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["scope_service"] is None
def test_create_rate_limit_success(self):
response = self.client.post(
diff --git a/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx b/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx
index 884f4c01660b..6340b19ed126 100644
--- a/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx
+++ b/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx
@@ -1,27 +1,160 @@
import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
-import { LemonInput, LemonSegmentedButton, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonInput, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+import { dataColorVars } from 'lib/colors'
+import { Sparkline, SparklineReferenceLine, SparklineTimeSeries } from 'lib/components/Sparkline'
+import { dayjs } from 'lib/dayjs'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
-import { ServiceFilter } from 'products/logs/frontend/components/LogsViewer/Filters/ServiceFilter'
import { RuleTypeEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { DropRuleFilterEditor } from './DropRuleFilterEditor'
-import { logsSamplingFormLogic } from './logsSamplingFormLogic'
+import { RateLimitUnit, logsSamplingFormLogic, rateLimitAmountToKbPerSecond } from './logsSamplingFormLogic'
+
+const RATE_LIMIT_UNIT_OPTIONS: { value: RateLimitUnit; label: string }[] = [
+ { value: 'KB/s', label: 'KB/s' },
+ { value: 'MB/s', label: 'MB/s' },
+ { value: 'GB/s', label: 'GB/s' },
+]
const ACTION_OPTIONS: { value: RuleTypeEnumApi; label: string }[] = [
{ value: RuleTypeEnumApi.PathDrop, label: 'Drop' },
{ value: RuleTypeEnumApi.RateLimit, label: 'Rate limit' },
]
+const TOP_SERVICES_LIMIT = 10
+
+interface SparklineSeriesData {
+ labels: string[]
+ series: SparklineTimeSeries[]
+ total: number
+ truncatedServiceCount: number
+ /** Width of one bar/bucket in seconds; needed to translate a per-second rate limit into per-bucket units. */
+ bucketSeconds: number
+ /** Tallest stacked total across buckets; used to position the rate-limit reference line. */
+ chartMax: number
+}
+
+type FilterPreviewPoint = { time: string; service: string; count: number; bytes_uncompressed?: number }
+
+function buildSparklineSeries(points: FilterPreviewPoint[] | null, metric: 'count' | 'bytes'): SparklineSeriesData {
+ if (!points || points.length === 0) {
+ return { labels: [], series: [], total: 0, truncatedServiceCount: 0, bucketSeconds: 0, chartMax: 0 }
+ }
+ const timeOrder: string[] = []
+ const seenTimes = new Set<string>()
+ const byService: Record<string, Map<string, number>> = {}
+ const serviceTotals = new Map<string, number>()
+ const bucketTotals = new Map<string, number>()
+ let total = 0
+ for (const point of points) {
+ if (!seenTimes.has(point.time)) {
+ seenTimes.add(point.time)
+ timeOrder.push(point.time)
+ }
+ const svc = point.service || 'unknown'
+ const value = metric === 'bytes' ? (point.bytes_uncompressed ?? 0) : point.count
+ const bucket = byService[svc] ?? (byService[svc] = new Map())
+ bucket.set(point.time, (bucket.get(point.time) ?? 0) + value)
+ serviceTotals.set(svc, (serviceTotals.get(svc) ?? 0) + value)
+ bucketTotals.set(point.time, (bucketTotals.get(point.time) ?? 0) + value)
+ total += value
+ }
+ const labels = timeOrder.map((t) => dayjs(t).format('D MMM HH:mm'))
+ const rankedServices = Array.from(serviceTotals.entries()).sort(([, a], [, b]) => b - a)
+ const topServices = rankedServices.slice(0, TOP_SERVICES_LIMIT)
+ const otherServices = rankedServices.slice(TOP_SERVICES_LIMIT)
+ const truncatedServiceCount = otherServices.length
+ const series: SparklineTimeSeries[] = topServices.map(([service], index) => ({
+ name: service,
+ color: dataColorVars[index % dataColorVars.length],
+ values: timeOrder.map((t) => byService[service]?.get(t) ?? 0),
+ }))
+ if (otherServices.length > 0) {
+ // Roll up the long tail into a single "Others" series so the chart still adds up to total volume,
+ // and the rate-limit reference line lines up against an honest stacked max.
+ const othersValues = timeOrder.map((t) =>
+ otherServices.reduce((sum, [service]) => sum + (byService[service]?.get(t) ?? 0), 0)
+ )
+ series.push({
+ name: `Others (${otherServices.length} services)`,
+ color: 'muted',
+ values: othersValues,
+ })
+ }
+ const bucketSeconds = timeOrder.length >= 2 ? dayjs(timeOrder[1]).diff(dayjs(timeOrder[0]), 'second') : 0
+ const chartMax = Math.max(0, ...Array.from(bucketTotals.values()))
+ return { labels, series, total, truncatedServiceCount, bucketSeconds, chartMax }
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1000) {
+ return `${bytes.toLocaleString()} B`
+ }
+ if (bytes < 1_000_000) {
+ return `${(bytes / 1000).toFixed(1)} KB`
+ }
+ if (bytes < 1_000_000_000) {
+ return `${(bytes / 1_000_000).toFixed(1)} MB`
+ }
+ return `${(bytes / 1_000_000_000).toFixed(2)} GB`
+}
+
export function LogsSamplingForm(): JSX.Element {
- const { samplingForm, samplingFormErrors, serviceTraffic, serviceTrafficLoading } = useValues(logsSamplingFormLogic)
+ const { samplingForm, samplingFormErrors, filterPreview, filterPreviewLoading } = useValues(logsSamplingFormLogic)
const { setSamplingFormValue } = useActions(logsSamplingFormLogic)
const isRateLimit = samplingForm.rule_type === RuleTypeEnumApi.RateLimit
+ const hasFilters = samplingForm.filter_group.values.length > 0
+
+ const matchDescription = isRateLimit
+ ? `Drop logs matching these filters above ${
+ samplingForm.rate_limit_amount.trim()
+ ? `${samplingForm.rate_limit_amount.trim()} ${samplingForm.rate_limit_unit}`
+ : 'the configured rate limit'
+ }.`
+ : 'Drop logs matching these filters. Dropped lines are not stored — they will not appear in the UI, exports, or alerts. Already-dropped data cannot be recovered.'
+
+ const previewMetric: 'count' | 'bytes' = isRateLimit ? 'bytes' : 'count'
+ const { labels, series, total, bucketSeconds, chartMax } = useMemo(
+ () => buildSparklineSeries(filterPreview, previewMetric),
+ [filterPreview, previewMetric]
+ )
+ const formattedTotal = previewMetric === 'bytes' ? formatBytes(total) : `${total.toLocaleString()} logs`
+
+ // Rate limit threshold projected onto the same y-axis units the chart uses (bytes/bucket).
+ const rateLimitThresholdPerBucket = useMemo<number | null>(() => {
+ if (!isRateLimit || bucketSeconds <= 0) {
+ return null
+ }
+ const kbPerSecond = rateLimitAmountToKbPerSecond(samplingForm.rate_limit_amount, samplingForm.rate_limit_unit)
+ if (!Number.isFinite(kbPerSecond) || kbPerSecond <= 0) {
+ return null
+ }
+ // KB/s × 1000 = bytes/s, × bucket width in seconds = bytes/bucket.
+ return kbPerSecond * 1000 * bucketSeconds
+ }, [isRateLimit, bucketSeconds, samplingForm.rate_limit_amount, samplingForm.rate_limit_unit])
+
+ const rateLimitReferenceLines = useMemo<SparklineReferenceLine[] | undefined>(() => {
+ if (rateLimitThresholdPerBucket == null) {
+ return undefined
+ }
+ return [
+ {
+ value: rateLimitThresholdPerBucket,
+ color: 'danger',
+ label: `Rate limit (${samplingForm.rate_limit_amount.trim()} ${samplingForm.rate_limit_unit})`,
+ labelPosition: 'end',
+ },
+ ]
+ }, [rateLimitThresholdPerBucket, samplingForm.rate_limit_amount, samplingForm.rate_limit_unit])
+
+ const rateLimitAboveChart =
+ rateLimitThresholdPerBucket != null && chartMax > 0 && rateLimitThresholdPerBucket > chartMax
return (
<div className="flex flex-col gap-4 max-w-3xl">
@@ -38,23 +171,6 @@ export function LogsSamplingForm(): JSX.Element {
</LemonField.Pure>
</div>
- <SceneSection
- title="Match"
- titleSize="sm"
- description="Drop logs matching these filters. Dropped lines are not stored — they will not appear in the UI, exports, or alerts. Already-dropped data cannot be recovered."
- >
- {isRateLimit ? (
- <p className="text-sm text-secondary m-0">
- Rate limit applies to every log line from the selected service — no per-line matcher.
- </p>
- ) : (
- <DropRuleFilterEditor
- filterGroup={samplingForm.filter_group}
- onChange={(group) => setSamplingFormValue('filter_group', group)}
- />
- )}
- </SceneSection>
-
<SceneSection title="Action" titleSize="sm">
<LemonField.Pure label="What to do when a log matches">
<LemonSegmentedButton
@@ -66,49 +182,77 @@ export function LogsSamplingForm(): JSX.Element {
</LemonField.Pure>
{isRateLimit && (
<LemonField.Pure
- label="Sustained limit (logs per second)"
- help="Whole number from 1 to 1,000,000. Burst capacity is set automatically (10× sustained)."
- error={samplingFormErrors.rate_limit_logs_per_second}
+ label="Rate limit"
+ help="Minimum 1 KB/s, maximum 1 GB/s. Fractional values allowed (e.g. 1.5 MB/s)."
+ error={samplingFormErrors.rate_limit_amount}
>
- <LemonInput
- value={samplingForm.rate_limit_logs_per_second}
- onChange={(v) => setSamplingFormValue('rate_limit_logs_per_second', v)}
- placeholder="e.g. 5000"
- className="max-w-xs"
- />
+ <div className="flex gap-2 items-center max-w-sm">
+ <LemonInput
+ value={samplingForm.rate_limit_amount}
+ onChange={(v) => setSamplingFormValue('rate_limit_amount', v)}
+ placeholder="e.g. 5"
+ inputMode="decimal"
+ />
+ <LemonSelect<RateLimitUnit>
+ value={samplingForm.rate_limit_unit}
+ onChange={(v) => v && setSamplingFormValue('rate_limit_unit', v)}
+ options={RATE_LIMIT_UNIT_OPTIONS}
+ />
+ </div>
</LemonField.Pure>
)}
</SceneSection>
- <SceneSection
- title="Scope"
- titleSize="sm"
- description="Limit this rule to one service, or apply it across the whole project."
- >
- <LemonField.Pure
- label={isRateLimit ? 'Service (required)' : 'Service (optional)'}
- error={samplingFormErrors.scope_service}
- help={isRateLimit ? 'Pick a service from the last 24h.' : 'Leave empty to apply to every service.'}
- >
- <div className="flex flex-col gap-2">
- <ServiceFilter
- selectionMode="single"
- emptyButtonLabel={isRateLimit ? 'Pick from last 24h…' : 'All services'}
- value={samplingForm.scope_service ? [samplingForm.scope_service] : []}
- onChange={(names) => setSamplingFormValue('scope_service', names[0] ?? '')}
- dateRange={{ date_from: '-24h', date_to: null }}
- />
- {isRateLimit &&
- (serviceTrafficLoading ? (
- <span className="text-muted text-sm">Loading recent volume…</span>
- ) : serviceTraffic && samplingForm.scope_service.trim() ? (
- <span className="text-muted text-sm">
- ~{serviceTraffic.avg_logs_per_sec.toFixed(2)} logs/sec average over the last 24h (
- {serviceTraffic.log_count.toLocaleString()} lines).
- </span>
- ) : null)}
+ <SceneSection title="Match" titleSize="sm" description={matchDescription}>
+ <DropRuleFilterEditor
+ filterGroup={samplingForm.filter_group}
+ onChange={(group) => setSamplingFormValue('filter_group', group)}
+ />
+ {/* filter_group is an object — kea-forms types only allow scalar field errors,
+ so this inline message mirrors what samplingFormSaveDisabledReason returns. */}
+ {!hasFilters && <p className="text-danger text-xs mt-1 mb-0">Add at least one filter to match logs.</p>}
+ <div className="mt-3 flex flex-col gap-1">
+ <div className="flex items-center justify-between text-xs text-muted">
+ <span>
+ Volume preview by service (last 24h, top {TOP_SERVICES_LIMIT}
+ {previewMetric === 'bytes' ? ', bytes' : ''})
+ </span>
+ {hasFilters && !filterPreviewLoading ? <span>{formattedTotal}</span> : null}
</div>
- </LemonField.Pure>
+ <div className="relative h-24 border border-border rounded-md bg-bg-light px-2 py-1">
+ {!hasFilters ? (
+ <div className="h-full flex items-center justify-center text-muted text-xs">
+ Add a filter above to preview matching log volume
+ </div>
+ ) : filterPreviewLoading || !filterPreview ? (
+ <Sparkline
+ data={[]}
+ labels={[]}
+ loading
+ className="w-full h-full"
+ maximumIndicator={false}
+ />
+ ) : series.length === 0 ? (
+ <div className="h-full flex items-center justify-center text-muted text-xs">
+ No logs match these filters in the last 24h
+ </div>
+ ) : (
+ <Sparkline
+ data={series}
+ labels={labels}
+ className="w-full h-full"
+ maximumIndicator={false}
+ referenceLines={rateLimitReferenceLines}
+ renderTooltipValue={previewMetric === 'bytes' ? formatBytes : undefined}
+ />
+ )}
+ </div>
+ {isRateLimit && rateLimitAboveChart ? (
+ <div className="text-xs text-muted">
+ Rate limit is above the current peak — no logs would be dropped in the previewed window.
+ </div>
+ ) : null}
+ </div>
</SceneSection>
</div>
)
diff --git a/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts b/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts
index 8cf1e62ee49d..f3144ef6eb91 100644
--- a/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts
+++ b/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts
@@ -5,15 +5,12 @@ import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
+import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
-import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+import { FilterLogicalOperator, PropertyGroupFilter, UniversalFiltersGroup } from '~/types'
-import {
- logsSamplingRulesCreate,
- logsSamplingRulesPartialUpdate,
- logsServicesCreate,
-} from 'products/logs/frontend/generated/api'
+import { logsSamplingRulesCreate, logsSamplingRulesPartialUpdate } from 'products/logs/frontend/generated/api'
import {
LogsSamplingRuleApi,
PatchedLogsSamplingRuleApi,
@@ -28,26 +25,67 @@ const EMPTY_FILTER_GROUP: UniversalFiltersGroup = {
values: [],
}
-// Burst capacity is no longer user-configurable — hardcoded to 10× sustained.
-// Backend follow-up will revisit this alongside the kB/s unit change.
+// Burst capacity is not user-configurable — hardcoded to 10× sustained.
const BURST_MULTIPLIER = 10
+export type RateLimitUnit = 'KB/s' | 'MB/s' | 'GB/s'
+
+/** Multiplier to convert the chosen unit into the wire-format unit (KB/s). */
+const UNIT_TO_KB_PER_S: Record<RateLimitUnit, number> = {
+ 'KB/s': 1,
+ 'MB/s': 1000,
+ 'GB/s': 1_000_000,
+}
+
+/** 1 KB/s minimum, 1 GB/s maximum, expressed in the wire-format unit (KB/s). */
+export const MIN_RATE_LIMIT_KB_PER_S = 1
+export const MAX_RATE_LIMIT_KB_PER_S = 1_000_000
+
export interface LogsSamplingFormType {
name: string
enabled: boolean
rule_type: RuleTypeEnumApi
- scope_service: string
filter_group: UniversalFiltersGroup
- rate_limit_logs_per_second: string
+ /** User-entered amount in the chosen unit. Fractional values are allowed. */
+ rate_limit_amount: string
+ rate_limit_unit: RateLimitUnit
}
const DEFAULT_FORM: LogsSamplingFormType = {
name: '',
enabled: true,
rule_type: RuleTypeEnumApi.PathDrop,
- scope_service: '',
filter_group: EMPTY_FILTER_GROUP,
- rate_limit_logs_per_second: '',
+ rate_limit_amount: '',
+ rate_limit_unit: 'MB/s',
+}
+
+/** Pick the largest unit that keeps the displayed amount ≥ 1 (and ≤ 999 where possible). */
+function chooseDisplayUnit(kbPerSecond: number): { amount: string; unit: RateLimitUnit } {
+ if (kbPerSecond >= UNIT_TO_KB_PER_S['GB/s']) {
+ return { amount: formatAmount(kbPerSecond / UNIT_TO_KB_PER_S['GB/s']), unit: 'GB/s' }
+ }
+ if (kbPerSecond >= UNIT_TO_KB_PER_S['MB/s']) {
+ return { amount: formatAmount(kbPerSecond / UNIT_TO_KB_PER_S['MB/s']), unit: 'MB/s' }
+ }
+ return { amount: formatAmount(kbPerSecond), unit: 'KB/s' }
+}
+
+/** Strip trailing zeros after a decimal point so 1500 KB/s round-trips as "1.5 MB/s", not "1.500000". */
+function formatAmount(value: number): string {
+ if (!Number.isFinite(value)) {
+ return ''
+ }
+ return Number(value.toFixed(6)).toString()
+}
+
+/** Convert a user-entered amount + unit into KB/s, rounded to the nearest integer. Returns NaN on invalid input. */
+export function rateLimitAmountToKbPerSecond(amount: string, unit: RateLimitUnit): number {
+ const parsed = parseFloat(amount.trim())
+ if (!Number.isFinite(parsed) || parsed <= 0) {
+ return Number.NaN
+ }
+ return Math.round(parsed * UNIT_TO_KB_PER_S[unit])
}
/** Read either the wrapped `{type, values: [innerGroup]}` (logs-viewer/alerts shape) or the bare inner group. */
@@ -71,6 +109,10 @@ function wrapFilterGroup(inner: UniversalFiltersGroup): UniversalFiltersGroup {
return { type: FilterLogicalOperator.And, values: [inner] as never }
}
+function isFilterGroupNonEmpty(group: UniversalFiltersGroup): boolean {
+ return Array.isArray(group.values) && group.values.length > 0
+}
+
export function buildSamplingFormDefaults(rule: LogsSamplingRuleApi | null): LogsSamplingFormType {
if (!rule) {
return { ...DEFAULT_FORM }
@@ -84,26 +126,26 @@ export function buildSamplingFormDefaults(rule: LogsSamplingRuleApi | null): Log
name: rule.name,
enabled: rule.enabled ?? false,
rule_type,
- scope_service: rule.scope_service ?? '',
- }
- if (rule_type === RuleTypeEnumApi.PathDrop) {
- form.filter_group = extractFilterGroup(cfg.filter_group)
}
+ form.filter_group = extractFilterGroup(cfg.filter_group)
if (rule_type === RuleTypeEnumApi.RateLimit) {
- form.rate_limit_logs_per_second =
- typeof cfg.logs_per_second === 'number' && !Number.isNaN(cfg.logs_per_second)
- ? String(cfg.logs_per_second)
- : ''
+ const stored = cfg.logs_per_second
+ if (typeof stored === 'number' && Number.isFinite(stored) && stored > 0) {
+ const { amount, unit } = chooseDisplayUnit(stored)
+ form.rate_limit_amount = amount
+ form.rate_limit_unit = unit
+ }
}
return form
}
export function buildSamplingConfigPayload(form: LogsSamplingFormType): Record<string, unknown> {
if (form.rule_type === RuleTypeEnumApi.RateLimit) {
- const lps = parseInt(form.rate_limit_logs_per_second.trim(), 10)
+ const lps = rateLimitAmountToKbPerSecond(form.rate_limit_amount, form.rate_limit_unit)
return {
logs_per_second: lps,
burst_logs: lps * BURST_MULTIPLIER,
+ filter_group: wrapFilterGroup(form.filter_group),
}
}
// `patterns: []` keeps the existing path_drop config validator happy.
@@ -130,87 +172,103 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([
})),
actions({
- refreshServiceTraffic: true,
+ refreshFilterPreview: true,
}),
loaders(({ values }) => ({
- serviceTraffic: [
- null as { log_count: number; avg_logs_per_sec: number } | null,
+ filterPreview: [
+ null as { time: string; service: string; count: number; bytes_uncompressed?: number }[] | null,
{
- loadServiceTraffic: async (_, breakpoint) => {
+ loadFilterPreview: async (_, breakpoint) => {
await breakpoint(400)
const form = values.samplingForm
- if (form.rule_type !== RuleTypeEnumApi.RateLimit) {
- return null
- }
- const svc = form.scope_service.trim()
- if (!svc) {
+ if (!isFilterGroupNonEmpty(form.filter_group)) {
return null
}
- const projectId = String(values.currentTeamId)
- const res = await logsServicesCreate(projectId, {
+ const response = await api.logs.sparkline({
query: {
dateRange: { date_from: '-24h', date_to: null },
- serviceNames: [svc],
+ filterGroup: wrapFilterGroup(form.filter_group) as PropertyGroupFilter,
+ severityLevels: [],
+ serviceNames: [],
+ sparklineBreakdownBy: 'service',
},
})
- const row = res.services.find((s) => s.service_name === svc)
- if (!row) {
- return { log_count: 0, avg_logs_per_sec: 0 }
- }
- const logCount = row.log_count
- return { log_count: logCount, avg_logs_per_sec: logCount / (24 * 3600) }
+ // The backend returns each row keyed by the breakdown value ('service' here),
+ // not by the underlying column name (service_name).
+ return response as {
+ time: string
+ service: string
+ count: number
+ bytes_uncompressed?: number
+ }[]
},
},
],
})),
listeners(({ actions }) => ({
- refreshServiceTraffic: () => {
- actions.loadServiceTraffic(null)
+ refreshFilterPreview: () => {
+ actions.loadFilterPreview(null)
},
- setSamplingFormValue: () => {
- actions.refreshServiceTraffic()
+ setSamplingFormValue: ({ name }) => {
+ if (name === 'filter_group') {
+ actions.refreshFilterPreview()
+ }
},
})),
- afterMount(({ actions }) => {
- actions.refreshServiceTraffic()
+ afterMount(({ actions, values }) => {
+ // Kick off an initial preview load on mount whenever the form is opened with
+ // a filter_group already set (edit mode, or pre-filled defaults). Without this
+ // the loader only fires on subsequent edits, leaving the sparkline stuck on
+ // "loading" because filterPreview is null and we never ran the request.
+ if (isFilterGroupNonEmpty(values.samplingForm.filter_group)) {
+ actions.refreshFilterPreview()
+ }
}),
forms(({ props, values }) => ({
samplingForm: {
defaults: buildSamplingFormDefaults(props.rule),
errors: (form: LogsSamplingFormType) => {
- const lps = parseInt(form.rate_limit_logs_per_second.trim(), 10)
+ let rateAmountError: string | undefined
+ if (form.rule_type === RuleTypeEnumApi.RateLimit) {
+ if (form.rate_limit_amount.trim() === '') {
+ rateAmountError = 'Enter a rate limit'
+ } else {
+ const parsed = parseFloat(form.rate_limit_amount.trim())
+ const kbPerSecond = rateLimitAmountToKbPerSecond(form.rate_limit_amount, form.rate_limit_unit)
+ if (!Number.isFinite(parsed) || parsed <= 0) {
+ rateAmountError = 'Enter a positive number'
+ } else if (parsed > 999) {
+ rateAmountError = 'Value must be at most 999 — switch to a larger unit if needed'
+ } else if (kbPerSecond < MIN_RATE_LIMIT_KB_PER_S) {
+ rateAmountError = 'Minimum rate limit is 1 KB/s'
+ } else if (kbPerSecond > MAX_RATE_LIMIT_KB_PER_S) {
+ rateAmountError = 'Maximum rate limit is 1 GB/s'
+ }
+ }
+ }
+ // kea-forms types scalar `errors` per field — filter_group is an object,
+ // so its validation lives in `samplingFormSaveDisabledReason` (consumed by
+ // the scene's submit button) and is displayed inline via the
+ // `filterGroupError` selector below.
return {
name: !form.name?.trim() ? 'Name is required' : undefined,
- scope_service:
- form.rule_type === RuleTypeEnumApi.RateLimit && !form.scope_service?.trim()
- ? 'Select or enter a service name'
- : undefined,
- rate_limit_logs_per_second:
- form.rule_type === RuleTypeEnumApi.RateLimit &&
- (form.rate_limit_logs_per_second.trim() === '' || Number.isNaN(lps) || lps < 1)
- ? 'Enter logs per second (integer ≥ 1)'
- : undefined,
+ rate_limit_amount: rateAmountError,
}
},
submit: async (form: LogsSamplingFormType) => {
- if (form.rule_type === RuleTypeEnumApi.PathDrop && form.filter_group.values.length === 0) {
- lemonToast.error('Add at least one filter to drop logs')
- return
- }
const projectId = String(values.currentTeamId)
try {
- const scope_service = form.scope_service.trim() || null
const scope_attribute_filters = (props.rule?.scope_attribute_filters ??
[]) as PatchedLogsSamplingRuleApi['scope_attribute_filters']
const payload = {
name: form.name.trim(),
enabled: form.enabled,
rule_type: form.rule_type,
- scope_service,
+ scope_service: null,
// scope_path_pattern is folded into the filter group; the backend column will be retired in PR 2.
scope_path_pattern: null,
scope_attribute_filters,
diff --git a/products/logs/frontend/components/LogsSampling/samplingFormSaveDisabledReason.ts b/products/logs/frontend/components/LogsSampling/samplingFormSaveDisabledReason.ts
index cad7a306e925..e45eb18a8a40 100644
--- a/products/logs/frontend/components/LogsSampling/samplingFormSaveDisabledReason.ts
+++ b/products/logs/frontend/components/LogsSampling/samplingFormSaveDisabledReason.ts
@@ -1,5 +1,3 @@
-import { RuleTypeEnumApi } from 'products/logs/frontend/generated/api.schemas'
-
import type { LogsSamplingFormType } from './logsSamplingFormLogic'
/**
@@ -10,8 +8,8 @@ import type { LogsSamplingFormType } from './logsSamplingFormLogic'
* and consumed directly by the scene's submit button.
*/
export function samplingFormSaveDisabledReason(form: LogsSamplingFormType): string | null {
- if (form.rule_type === RuleTypeEnumApi.PathDrop && form.filter_group.values.length === 0) {
- return 'Add at least one filter to drop logs'
+ if (form.filter_group.values.length === 0) {
+ return 'Add at least one filter to match logs'
}
return null
}
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 4b268369be0e..07bebd452d1d 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1160,14 +1160,14 @@ export interface LogsSamplingRuleApi {
* @nullable
*/
priority?: number | null
- /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).
+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).
* `severity_sampling` - Severity-based reduction
* `path_drop` - Path exclusion
* `rate_limit` - Rate limit */
rule_type: RuleTypeEnumApi
/**
- * If set, the rule applies only to this service name; null means all services.
+ * Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.
* @maxLength 512
* @nullable
*/
@@ -1180,7 +1180,7 @@ export interface LogsSamplingRuleApi {
scope_path_pattern?: string | null
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: LogsSamplingRuleApiScopeAttributeFiltersItem[]
- /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB/s, 1–1000000 = 1 GB/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to. */
config: unknown
/** Incremented on each update for worker cache coherency. */
readonly version: number
@@ -1217,14 +1217,14 @@ export interface PatchedLogsSamplingRuleApi {
* @nullable
*/
priority?: number | null
- /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).
+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).
* `severity_sampling` - Severity-based reduction
* `path_drop` - Path exclusion
* `rate_limit` - Rate limit */
rule_type?: RuleTypeEnumApi
/**
- * If set, the rule applies only to this service name; null means all services.
+ * Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.
* @maxLength 512
* @nullable
*/
@@ -1237,7 +1237,7 @@ export interface PatchedLogsSamplingRuleApi {
scope_path_pattern?: string | null
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: PatchedLogsSamplingRuleApiScopeAttributeFiltersItem[]
- /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB/s, 1–1000000 = 1 GB/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to. */
config?: unknown
/** Incremented on each update for worker cache coherency. */
readonly version?: number
@@ -1372,6 +1372,8 @@ export interface _LogsSparklineBucketApi {
/** Service name when sparklineBreakdownBy="service". Present only for service-broken-down sparklines. */
service?: string
count: number
+ /** Sum of uncompressed bytes for the bucket. */
+ bytes_uncompressed?: number
}
export interface _LogsSparklineResponseApi {
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 0f150aba0e42..e55e032eca47 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -776,13 +776,13 @@ export const LogsSamplingRulesCreateBody = /* @__PURE__ */ zod.object({
'\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
)
.describe(
- 'Rule kind: severity_sampling, path_drop, or rate_limit (caps logs\/sec for scope_service at ingestion).\n\n\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
+ 'Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).\n\n\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
),
scope_service: zod
.string()
.max(logsSamplingRulesCreateBodyScopeServiceMax)
.nullish()
- .describe('If set, the rule applies only to this service name; null means all services.'),
+ .describe('Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.'),
scope_path_pattern: zod
.string()
.max(logsSamplingRulesCreateBodyScopePathPatternMax)
@@ -797,7 +797,7 @@ export const LogsSamplingRulesCreateBody = /* @__PURE__ */ zod.object({
config: zod
.unknown()
.describe(
- 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
+ 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB\/s, 1–1000000 = 1 GB\/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to.'
),
})
@@ -829,13 +829,13 @@ export const LogsSamplingRulesUpdateBody = /* @__PURE__ */ zod.object({
'\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
)
.describe(
- 'Rule kind: severity_sampling, path_drop, or rate_limit (caps logs\/sec for scope_service at ingestion).\n\n\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
+ 'Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).\n\n\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
),
scope_service: zod
.string()
.max(logsSamplingRulesUpdateBodyScopeServiceMax)
.nullish()
- .describe('If set, the rule applies only to this service name; null means all services.'),
+ .describe('Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.'),
scope_path_pattern: zod
.string()
.max(logsSamplingRulesUpdateBodyScopePathPatternMax)
@@ -850,7 +850,7 @@ export const LogsSamplingRulesUpdateBody = /* @__PURE__ */ zod.object({
config: zod
.unknown()
.describe(
- 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
+ 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB\/s, 1–1000000 = 1 GB\/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to.'
),
})
@@ -887,13 +887,13 @@ export const LogsSamplingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- 'Rule kind: severity_sampling, path_drop, or rate_limit (caps logs\/sec for scope_service at ingestion).\n\n\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
+ 'Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).\n\n\* `severity_sampling` - Severity-based reduction\n\* `path_drop` - Path exclusion\n\* `rate_limit` - Rate limit'
),
scope_service: zod
.string()
.max(logsSamplingRulesPartialUpdateBodyScopeServiceMax)
.nullish()
- .describe('If set, the rule applies only to this service name; null means all services.'),
+ .describe('Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.'),
scope_path_pattern: zod
.string()
.max(logsSamplingRulesPartialUpdateBodyScopePathPatternMax)
@@ -909,7 +909,7 @@ export const LogsSamplingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'
+ 'Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND\/OR tree of property predicates evaluated per record) and\/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB\/s, 1–1000000 = 1 GB\/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to.'
),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 736dfe6e4768..14276af03728 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20395,14 +20395,14 @@ export namespace Schemas {
* @nullable
*/
priority?: number | null;
- /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).
+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).
* `severity_sampling` - Severity-based reduction
* `path_drop` - Path exclusion
* `rate_limit` - Rate limit */
rule_type: RuleTypeEnum;
/**
- * If set, the rule applies only to this service name; null means all services.
+ * Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.
* @maxLength 512
* @nullable
*/
@@ -20415,7 +20415,7 @@ export namespace Schemas {
scope_path_pattern?: string | null;
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: LogsSamplingRuleScopeAttributeFiltersItem[];
- /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB/s, 1–1000000 = 1 GB/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to. */
config: unknown;
/** Incremented on each update for worker cache coherency. */
readonly version: number;
@@ -28095,14 +28095,14 @@ export namespace Schemas {
* @nullable
*/
priority?: number | null;
- /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).
+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps matching log volume at ingestion).
* `severity_sampling` - Severity-based reduction
* `path_drop` - Path exclusion
* `rate_limit` - Rate limit */
rule_type?: RuleTypeEnum;
/**
- * If set, the rule applies only to this service name; null means all services.
+ * Optional legacy service-name scope; new rules use `config.filter_group` for matching instead.
* @maxLength 512
* @nullable
*/
@@ -28115,7 +28115,7 @@ export namespace Schemas {
scope_path_pattern?: string | null;
/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */
scope_attribute_filters?: PatchedLogsSamplingRuleScopeAttributeFiltersItem[];
- /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */
+ /** Type-specific JSON. For path_drop: object with optional `filter_group` (PropertyGroupFilter shape — AND/OR tree of property predicates evaluated per record) and/or legacy `patterns` (list of regex strings) + `match_attribute_key` (string). When both are present a record is dropped if EITHER matches. Filter group example: `{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}`. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer KB/s, 1–1000000 = 1 GB/s) and optional `burst_logs` (integer KB ≥ logs_per_second, max 10000000) and optional `filter_group` to narrow which logs the cap applies to. */
config?: unknown;
/** Incremented on each update for worker cache coherency. */
readonly version?: number;
@@ -37009,6 +37009,8 @@ export namespace Schemas {
/** Service name when sparklineBreakdownBy="service". Present only for service-broken-down sparklines. */
service?: string;
count: number;
+ /** Sum of uncompressed bytes for the bucket. */
+ bytes_uncompressed?: number;
}
export interface _LogsSparklineRequest {