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.

fix(logs): make pattern sampling bounded, deterministic, and honest (#67751)

Jon McCallum30815070a2a2
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index a1558742efa0..929f02cefd57 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -138,6 +138,10 @@ class HogQLGlobalSettings(HogQLQuerySettings):
model_config = ConfigDict(extra="forbid")
readonly: Optional[int] = 2
max_execution_time: Optional[int] = 60
+ # None inherits the cluster profile's overflow behavior. Set "throw" when a partial
+ # result is worse than an error (e.g. sampling queries whose output feeds further
+ # computation), or "break" to accept partial results on timeout.
+ timeout_overflow_mode: Optional[str] = None
max_memory_usage: Optional[int] = None # default value coming from cloud config
max_threads: Optional[int] = None
allow_experimental_object_type: Optional[bool] = True
diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.py
index 3e14b6370855..c9c225fe92e5 100644
--- a/products/logs/backend/patterns_query_runner.py
+++ b/products/logs/backend/patterns_query_runner.py
@@ -19,14 +19,33 @@ from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQuery
if TYPE_CHECKING:
from posthog.models import User
+_TimeSlice = tuple[dt.datetime, dt.datetime]
+
class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):
- """Mines log templates (Drain3) from an evenly-distributed sample of the matching logs.
+ """Mines log templates (Drain3) from a bounded, deterministic sample of the matching logs.
+
+ The sampling has to respect two constraints at once:
+
+ * A uniform per-row sampling predicate cannot be short-circuited by LIMIT — ClickHouse
+ has to scan (and decompress `body` for) the whole eligible range to find the matches.
+ On high-volume windows that blows the wall-clock budget, and a timed-out scan that
+ returns partially is worse than an error: it silently mines patterns from whatever
+ handful of rows the scan reached. So the rows eligible for sampling are capped at
+ `LOGS_PATTERNS_MAX_SCAN_ROWS` via stratified time slices — evenly spaced sub-windows
+ (`LOGS_PATTERNS_SLICE_COUNT` of them, the last aligned to the window end) that keep
+ the sample spread across the window while bounding what the query may read. As a
+ backstop, `timeout_overflow_mode="throw"` turns any remaining timeout into an error
+ instead of a truncated sample.
- Sampling keeps clustering cheap on large windows: we count the matching rows, then pull
- at most `LOGS_PATTERNS_SAMPLE_LIMIT` of them spread across the window via a random-modulo
- predicate, and feed those bodies to `mine_patterns`. `sampled` is True whenever the
- window held more rows than the sample cap.
+ * Results should be reproducible: the same filters over the same window must mine the
+ same patterns. The sampling predicate hashes the row's immutable `uuid`
+ (`cityHash64(uuid) % divisor = 0`) rather than using `rand()`, so the sample — and
+ therefore the mined patterns — is a pure function of the data and the divisor.
+
+ `sampled` is True whenever fewer rows were scanned than the window held — i.e. whenever
+ the reported per-pattern counts are extrapolated estimates rather than exact tallies,
+ whether the scan was narrowed by hash-mod sampling or by the time slices (or both).
"""
query: LogsQuery
@@ -35,18 +54,28 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
@cached_property
def settings(self) -> HogQLGlobalSettings:
# Bytes are intentionally uncapped: a hard `max_bytes_to_read` + "throw" cap 500s on
- # wide windows (the symbol-stats read-cap cliff), so we bound by wall-clock instead
- # and let the sample query's LIMIT short-circuit the scan.
+ # wide windows (the symbol-stats read-cap cliff). The scan is bounded by the time
+ # slices instead; timeout_overflow_mode="throw" guarantees a slow scan surfaces as
+ # an error rather than silently mining from a partial sample.
return HogQLGlobalSettings(
max_execution_time=_env("LOGS_PATTERNS_MAX_EXECUTION_TIME", 60, int),
max_bytes_to_read=None,
read_overflow_mode=None,
+ timeout_overflow_mode="throw",
)
@cached_property
def _sample_limit(self) -> int:
return _env("LOGS_PATTERNS_SAMPLE_LIMIT", 10000, int)
+ @cached_property
+ def _scan_budget(self) -> int:
+ return _env("LOGS_PATTERNS_MAX_SCAN_ROWS", 2_000_000, int)
+
+ @cached_property
+ def _slice_count(self) -> int:
+ return _env("LOGS_PATTERNS_SLICE_COUNT", 12, int)
+
def validate_query_runner_access(self, user: "User") -> bool:
# Defensive: this runner is invoked directly via the logs API, never through the generic
# /api/projects/:id/query/ endpoint. Mirror LogsQueryRunner and refuse user-initiated
@@ -57,10 +86,20 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
def _calculate(self) -> LogsQueryResponse:
total = self._count()
- sampled = total > self._sample_limit
- divisor = _sample_divisor(total, self._sample_limit)
- response = self._execute(self._sample_query(divisor))
+ slices = _time_slices(
+ self.query_date_range.date_from(),
+ self.query_date_range.date_to(),
+ total=total,
+ scan_budget=self._scan_budget,
+ slice_count=self._slice_count,
+ )
+ # The slice row count is exact (counts don't read `body`, so a second count is cheap),
+ # which keeps the divisor honest even when log volume is bursty across the window.
+ pool = self._count(slices) if slices is not None else total
+ divisor = _sample_divisor(pool, self._sample_limit)
+
+ response = self._execute(self._sample_query(divisor, slices))
samples = [
LogSample(
body=row[0],
@@ -71,12 +110,17 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
for row in response.results
]
patterns = mine_patterns(samples)
+ # `sampled` mirrors the exact condition `_serialize` uses to extrapolate: it's True
+ # whenever fewer rows were scanned than the window held (hash-mod sampling OR time-slice
+ # bounding), so the flag can never diverge from whether the reported counts are estimates.
+ scanned = len(samples)
return LogsQueryResponse(
results={
- "patterns": [_serialize(p) for p in patterns],
- "scanned_count": len(samples),
+ "patterns": [_serialize(p, total_count=total, scanned_count=scanned) for p in patterns],
+ "scanned_count": scanned,
"total_count": total,
- "sampled": sampled,
+ "sampled": scanned < total,
+ "sample_coverage_pct": round(pool / total * 100, 2) if total else 100.0,
}
)
@@ -87,8 +131,8 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
def to_query(self) -> ast.SelectQuery:
# Canonical (unsampled) form for the base runner's query contract; _calculate picks
- # the runtime divisor.
- return self._sample_query(divisor=1)
+ # the runtime divisor and slices.
+ return self._sample_query(divisor=1, slices=None)
def _execute(self, query: ast.SelectQuery | ast.SelectSetQuery):
return execute_hogql_query(
@@ -102,41 +146,60 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
settings=self.settings,
)
- def _count(self) -> int:
+ def _count(self, slices: list[_TimeSlice] | None = None) -> int:
response = self._execute(
parse_select(
"SELECT count() FROM logs WHERE {where}",
- placeholders={"where": self._where_with_timestamp()},
+ placeholders={"where": self._where_with_timestamp(slices)},
)
)
return int(response.results[0][0]) if response.results else 0
- def _where_with_timestamp(self) -> ast.Expr:
+ def _where_with_timestamp(self, slices: list[_TimeSlice] | None = None) -> ast.Expr:
# LogsFilterBuilder.where() filters at day-precision via time_bucket; add explicit
# per-row timestamp bounds (half-open) so the sample matches the requested window.
- return ast.And(
- exprs=[
- self.where(),
- parse_expr(
- "timestamp >= {date_from} AND timestamp < {date_to}",
- placeholders={
- "date_from": ast.Constant(value=self.query_date_range.date_from()),
- "date_to": ast.Constant(value=self.query_date_range.date_to()),
- },
- ),
- ]
- )
+ exprs: list[ast.Expr] = [
+ self.where(),
+ parse_expr(
+ "timestamp >= {date_from} AND timestamp < {date_to}",
+ placeholders={
+ "date_from": ast.Constant(value=self.query_date_range.date_from()),
+ "date_to": ast.Constant(value=self.query_date_range.date_to()),
+ },
+ ),
+ ]
+ if slices is not None:
+ # Slice bounds are on `timestamp` (in the sort key), so ClickHouse prunes the
+ # granules outside the slices instead of scanning the whole window.
+ exprs.append(
+ ast.Or(
+ exprs=[
+ parse_expr(
+ "timestamp >= {slice_from} AND timestamp < {slice_to}",
+ placeholders={
+ "slice_from": ast.Constant(value=slice_from),
+ "slice_to": ast.Constant(value=slice_to),
+ },
+ )
+ for slice_from, slice_to in slices
+ ]
+ )
+ )
+ return ast.And(exprs=exprs)
- def _sample_query(self, divisor: int) -> ast.SelectQuery:
- # Even-random sampling: rand() is per-row uniform and independent of timestamp, so
- # `rand() % divisor = 0` keeps ~1/divisor of rows spread evenly across the window.
- # divisor == 1 means no sampling, so we skip the modulo predicate entirely.
- where: ast.Expr = self._where_with_timestamp()
+ def _sample_query(self, divisor: int, slices: list[_TimeSlice] | None = None) -> ast.SelectQuery:
+ # Deterministic even-random sampling: cityHash64(uuid) is uniform and fixed per row,
+ # so `% divisor = 0` keeps ~1/divisor of rows spread evenly across the slices AND the
+ # same rows on every run. divisor == 1 means no sampling, so we skip the predicate.
+ where: ast.Expr = self._where_with_timestamp(slices)
if divisor > 1:
where = ast.And(
exprs=[
where,
- parse_expr("rand() % {divisor} = 0", placeholders={"divisor": ast.Constant(value=divisor)}),
+ parse_expr(
+ "cityHash64(uuid) % {divisor} = 0",
+ placeholders={"divisor": ast.Constant(value=divisor)},
+ ),
]
)
query = parse_select(
@@ -152,20 +215,57 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
return query
+def _time_slices(
+ date_from: dt.datetime,
+ date_to: dt.datetime,
+ *,
+ total: int,
+ scan_budget: int,
+ slice_count: int,
+) -> list[_TimeSlice] | None:
+ """Evenly spaced sub-windows covering ~scan_budget/total of [date_from, date_to).
+
+ Returns None when the whole window fits the budget. The last slice is aligned to end at
+ date_to so the freshest logs are always eligible for the sample.
+ """
+ if total <= scan_budget:
+ return None
+ window = date_to - date_from
+ if window <= dt.timedelta(0):
+ return None
+ slice_count = max(1, slice_count)
+ step = window / slice_count
+ width = window * (scan_budget / total) / slice_count
+ slices = []
+ for i in range(slice_count):
+ end = date_from + step * (i + 1)
+ slices.append((end - width, end))
+ return slices
+
+
def _sample_divisor(total: int, sample_limit: int) -> int:
- # Round up so total / divisor <= sample_limit: the rand()-modulo predicate alone bounds the
- # sample and LIMIT never truncates the random subset in (biased) read order.
+ # Round up so total / divisor <= sample_limit: the hash-modulo predicate alone bounds the
+ # sample and LIMIT never truncates the subset in (biased) read order.
if total <= sample_limit:
return 1
return ceil(total / sample_limit)
-def _serialize(pattern: MinedPattern) -> dict:
+def _serialize(pattern: MinedPattern, *, total_count: int, scanned_count: int) -> dict:
+ # Extrapolate sample counts to the full window so consumers don't have to; when the
+ # window wasn't sampled the estimates are the exact counts.
+ def estimate(sample_count: int) -> int:
+ if scanned_count >= total_count:
+ return sample_count
+ return round(sample_count / scanned_count * total_count)
+
return {
"pattern": pattern.pattern,
"count": pattern.count,
+ "estimated_count": estimate(pattern.count),
"volume_share_pct": pattern.volume_share_pct,
"error_count": pattern.error_count,
+ "estimated_error_count": estimate(pattern.error_count),
"first_seen": pattern.first_seen.isoformat(),
"last_seen": pattern.last_seen.isoformat(),
"examples": pattern.examples,
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index 72f0f044b14c..a88cf92d78f0 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -671,14 +671,26 @@ class _LogPatternSerializer(serializers.Serializer):
count = serializers.IntegerField(
help_text=(
"Occurrences of this pattern within the sample. When `sampled` is true this is a sample "
- "count, not the full-window total — scale by `total_count / scanned_count` to estimate."
+ "count, not the full-window total — prefer `estimated_count` for display."
+ ),
+ )
+ estimated_count = serializers.IntegerField(
+ help_text=(
+ "Estimated occurrences across the full window, extrapolated from the sample "
+ "(`count / scanned_count * total_count`). Equals `count` when the window was not sampled."
),
)
volume_share_pct = serializers.FloatField(
help_text="Share of the sampled log volume this pattern represents (0–100).",
)
error_count = serializers.IntegerField(
- help_text='Sampled occurrences at severity "error" or "fatal".',
+ help_text='Sampled occurrences at severity "error" or "fatal". Prefer `estimated_error_count` for display.',
+ )
+ estimated_error_count = serializers.IntegerField(
+ help_text=(
+ "Estimated error/fatal occurrences across the full window, extrapolated from the sample. "
+ "Equals `error_count` when the window was not sampled."
+ ),
)
first_seen = serializers.CharField(help_text="ISO 8601 timestamp of the earliest sampled occurrence.")
last_seen = serializers.CharField(help_text="ISO 8601 timestamp of the latest sampled occurrence.")
@@ -709,7 +721,14 @@ class _LogsPatternsResponseSerializer(serializers.Serializer):
sampled = serializers.BooleanField(
help_text=(
"True when the window held more rows than the sample cap, so patterns were mined from "
- "an evenly-distributed random sample rather than every matching row."
+ "a deterministic, evenly-distributed sample rather than every matching row."
+ ),
+ )
+ sample_coverage_pct = serializers.FloatField(
+ help_text=(
+ "Share of the window's log rows that were eligible for sampling (0–100). Below 100, "
+ "the scan was bounded to evenly-spaced time slices across the window to keep the "
+ "query within its execution budget; rows outside the slices could not appear in the sample."
),
)
diff --git a/products/logs/backend/test/test_patterns_api.py b/products/logs/backend/test/test_patterns_api.py
index 6f3936f9ffa3..eb5781173d97 100644
--- a/products/logs/backend/test/test_patterns_api.py
+++ b/products/logs/backend/test/test_patterns_api.py
@@ -42,9 +42,12 @@ class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):
assert body["scanned_count"] == 3
assert body["total_count"] == 3
assert body["sampled"] is False
+ assert body["sample_coverage_pct"] == 100.0
pattern = next(p for p in body["patterns"] if p["pattern"] == "User <*> not found")
assert pattern["count"] == 3
+ assert pattern["estimated_count"] == 3
assert pattern["error_count"] == 3
+ assert pattern["estimated_error_count"] == 3
assert pattern["services"] == ["auth"]
@freeze_time("2026-06-23T13:00:00Z")
diff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.py
index 40d8501ce36f..ad71de33aaba 100644
--- a/products/logs/backend/test/test_patterns_query_runner.py
+++ b/products/logs/backend/test/test_patterns_query_runner.py
@@ -1,5 +1,6 @@
import os
import json
+import datetime as dt
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
@@ -12,7 +13,7 @@ from posthog.schema import DateRange, FilterLogicalOperator, LogsQuery, Property
from posthog.clickhouse.client import sync_execute
from posthog.hogql_queries.query_runner import ExecutionMode
-from products.logs.backend.patterns_query_runner import PatternsQueryRunner, _sample_divisor
+from products.logs.backend.patterns_query_runner import PatternsQueryRunner, _sample_divisor, _time_slices
_FROZEN_NOW = "2026-06-23T13:00:00Z"
_WINDOW = DateRange(date_from="2026-06-23T00:00:00Z", date_to="2026-06-23T13:00:00Z")
@@ -58,18 +59,20 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert results["scanned_count"] == 5
assert results["total_count"] == 5
assert results["sampled"] is False
+ assert results["sample_coverage_pct"] == 100.0
by_template = {p["pattern"]: p for p in patterns}
assert "User <*> not found" in by_template
assert by_template["User <*> not found"]["count"] == 3
+ # Unsampled window: estimates equal exact counts.
+ assert by_template["User <*> not found"]["estimated_count"] == 3
assert by_template["User <*> not found"]["error_count"] == 3
+ assert by_template["User <*> not found"]["estimated_error_count"] == 3
assert by_template["User <*> not found"]["services"] == ["auth"]
@freeze_time(_FROZEN_NOW)
def test_sets_sampled_and_caps_scanned_count_above_the_limit(self) -> None:
self._insert([self._log(f"request {i} handled") for i in range(20)])
- # Only assert invariants that don't depend on the random sample: `sampled` is a
- # deterministic function of total vs. limit, and the LIMIT caps `scanned_count`.
with patch.dict(os.environ, {"LOGS_PATTERNS_SAMPLE_LIMIT": "5"}):
results = self._run()
@@ -78,6 +81,77 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# total_count reports the full window size even though the sample is capped.
assert results["total_count"] == 20
+ @freeze_time(_FROZEN_NOW)
+ def test_sampled_runs_are_deterministic(self) -> None:
+ # The sample hashes each row's immutable uuid rather than using rand(), so the same
+ # window + filters must mine identical patterns on every run. Guards against
+ # reintroducing per-query randomness, which made sampled results unreproducible.
+ self._insert([self._log(f"job {chr(97 + i)} finished with status ok") for i in range(40)])
+
+ with patch.dict(os.environ, {"LOGS_PATTERNS_SAMPLE_LIMIT": "20"}):
+ first = self._run()
+ second = self._run()
+
+ assert first["sampled"] is True
+ assert first["patterns"] == second["patterns"]
+ assert first["scanned_count"] == second["scanned_count"]
+
+ @freeze_time(_FROZEN_NOW)
+ def test_scan_budget_bounds_eligible_rows_via_time_slices(self) -> None:
+ # 60 rows, one per minute across a 1h window; a budget of 30 with 6 slices makes only
+ # half the window eligible. No hash sampling kicks in (pool < sample limit), so the
+ # run is fully deterministic: every eligible row is scanned, and estimates scale the
+ # sample back up to the window total. The counts are still extrapolated (30 scanned of
+ # 60), so `sampled` must stay True even though hash-mod sampling never activated —
+ # otherwise the UI renders the estimates as exact.
+ self._insert([self._log("tick", minute=m) for m in range(60)])
+ window = DateRange(date_from="2026-06-23T12:00:00Z", date_to="2026-06-23T13:00:00Z")
+
+ with patch.dict(os.environ, {"LOGS_PATTERNS_MAX_SCAN_ROWS": "30", "LOGS_PATTERNS_SLICE_COUNT": "6"}):
+ results = self._run(dateRange=window)
+
+ assert results["total_count"] == 60
+ assert results["scanned_count"] == 30
+ assert results["sample_coverage_pct"] == 50.0
+ assert results["sampled"] is True
+ (pattern,) = results["patterns"]
+ assert pattern["count"] == 30
+ assert pattern["estimated_count"] == 60
+
+ @parameterized.expand(
+ [
+ ("under_budget", 100, 200, None),
+ ("at_budget", 100, 100, None),
+ ]
+ )
+ def test_time_slices_skipped_when_window_fits_budget(self, _name, total, budget, expected) -> None:
+ assert (
+ _time_slices(
+ dt.datetime(2026, 6, 23, 0, 0),
+ dt.datetime(2026, 6, 23, 1, 0),
+ total=total,
+ scan_budget=budget,
+ slice_count=4,
+ )
+ is expected
+ )
+
+ def test_time_slices_cover_budget_fraction_and_align_to_window_end(self) -> None:
+ date_from = dt.datetime(2026, 6, 23, 0, 0)
+ date_to = dt.datetime(2026, 6, 23, 1, 0)
+
+ slices = _time_slices(date_from, date_to, total=200, scan_budget=100, slice_count=4)
+
+ assert slices is not None
+ assert len(slices) == 4
+ # Coverage 0.5 over 60min in 4 slices -> each slice is 7.5min wide.
+ assert all(end - start == dt.timedelta(minutes=7.5) for start, end in slices)
+ # Last slice ends at the window end so the freshest logs stay eligible.
+ assert slices[-1][1] == date_to
+ # Slices stay within the window and don't overlap.
+ assert slices[0][0] >= date_from
+ assert all(slices[i][1] <= slices[i + 1][0] for i in range(len(slices) - 1))
+
@parameterized.expand(
[
(0, 1),
diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
index f308c79346d5..df54be266ac4 100644
--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
@@ -30,7 +30,11 @@ function renderPatternTemplate(pattern: string): JSX.Element {
}
export function LogsPatterns({ id }: { id: string }): JSX.Element {
- const { patterns, patternsResponseLoading } = useValues(logsPatternsLogic({ id }))
+ const { patterns, patternsResponse, patternsResponseLoading, patternsError } = useValues(logsPatternsLogic({ id }))
+ const { sampled, scanned_count, total_count, sample_coverage_pct } = patternsResponse
+
+ // Estimated counts get a "~" so a reader never mistakes an extrapolation for a measurement.
+ const renderEstimate = (value: number): string => `${sampled ? '~' : ''}${humanFriendlyNumber(value)}`
const columns: LemonTableColumns<_LogPatternApi> = [
{
@@ -40,9 +44,9 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {
},
{
title: 'Count',
- dataIndex: 'count',
- render: (_, row) => humanFriendlyNumber(row.count),
- sorter: (a, b) => a.count - b.count,
+ dataIndex: 'estimated_count',
+ render: (_, row) => renderEstimate(row.estimated_count),
+ sorter: (a, b) => a.estimated_count - b.estimated_count,
align: 'right',
},
{
@@ -54,14 +58,14 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {
},
{
title: 'Errors',
- dataIndex: 'error_count',
+ dataIndex: 'estimated_error_count',
render: (_, row) =>
- row.error_count > 0 ? (
- <LemonTag type="danger">{humanFriendlyNumber(row.error_count)}</LemonTag>
+ row.estimated_error_count > 0 ? (
+ <LemonTag type="danger">{renderEstimate(row.estimated_error_count)}</LemonTag>
) : (
<span className="text-muted">0</span>
),
- sorter: (a, b) => a.error_count - b.error_count,
+ sorter: (a, b) => a.estimated_error_count - b.estimated_error_count,
align: 'right',
},
{
@@ -84,12 +88,26 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {
return (
<div className="flex-1 min-h-0 overflow-auto" data-attr="logs-patterns">
+ {sampled && !patternsResponseLoading && !patternsError && (
+ <div className="text-muted text-xs px-2 py-1" data-attr="logs-patterns-sample-info">
+ Mined from a sample of {humanFriendlyNumber(scanned_count)} of {humanFriendlyNumber(total_count)}{' '}
+ lines
+ {sample_coverage_pct < 100
+ ? `, drawn from evenly-spaced slices covering ${sample_coverage_pct.toFixed(1)}% of the window`
+ : ''}
+ . Counts are estimates.
+ </div>
+ )}
<LemonTable
columns={columns}
dataSource={patterns}
loading={patternsResponseLoading}
- defaultSorting={{ columnKey: 'count', order: -1 }}
- emptyState="No patterns found for the current filters"
+ defaultSorting={{ columnKey: 'estimated_count', order: -1 }}
+ emptyState={
+ patternsError
+ ? 'Pattern analysis failed — try a shorter time range or narrower filters'
+ : 'No patterns found for the current filters'
+ }
rowKey="pattern"
size="small"
/>
diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
index 5b774fc2e4cf..2aafd63fb8c9 100644
--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
@@ -23,8 +23,10 @@ const RESPONSE: _LogsPatternsResponseApi = {
{
pattern: 'User <*> not found',
count: 3,
+ estimated_count: 3,
volume_share_pct: 75,
error_count: 3,
+ estimated_error_count: 3,
first_seen: '2026-06-23T12:00:00+00:00',
last_seen: '2026-06-23T12:05:00+00:00',
examples: [],
@@ -34,6 +36,7 @@ const RESPONSE: _LogsPatternsResponseApi = {
scanned_count: 3,
total_count: 3,
sampled: false,
+ sample_coverage_pct: 100,
}
describe('logsPatternsLogic', () => {
@@ -64,6 +67,20 @@ describe('logsPatternsLogic', () => {
)
})
+ it('surfaces a load failure as patternsError and clears it on the next success', async () => {
+ // A failed mine (e.g. sampling query over budget) must not render as "no patterns".
+ mockCreate.mockRejectedValueOnce(new Error('estimated query execution time is too long'))
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadPatterns', 'loadPatternsFailure'])
+ expect(logic.values.patternsError).toBeTruthy()
+
+ await expectLogic(logic, () => {
+ logic.actions.loadPatterns()
+ }).toDispatchActions(['loadPatternsSuccess'])
+ expect(logic.values.patternsError).toBeNull()
+ })
+
it('reloads when a shared filter changes', async () => {
logic.mount()
await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])
diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
index 44265a2c4f8b..30894885f25c 100644
--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
@@ -1,4 +1,4 @@
-import { afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'
+import { afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
@@ -22,6 +22,7 @@ const EMPTY_RESPONSE: _LogsPatternsResponseApi = {
scanned_count: 0,
total_count: 0,
sampled: false,
+ sample_coverage_pct: 100,
}
// Keyed by the Viewer's `id`: the logic mounts only while the Patterns mode is active (the
@@ -77,6 +78,19 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
],
})),
+ // A failed mine (e.g. the sampling query exceeding its execution budget) must surface as
+ // an error, not render as "no patterns found" — that would misrepresent the data.
+ reducers({
+ patternsError: [
+ null as string | null,
+ {
+ loadPatterns: () => null,
+ loadPatternsSuccess: () => null,
+ loadPatternsFailure: (_, { error }) => error ?? 'Pattern analysis failed',
+ },
+ ],
+ }),
+
selectors({
patterns: [
(s) => [s.patternsResponse],
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index ebb078efe6bd..eb3a52906188 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1073,12 +1073,16 @@ export interface _LogsPatternsRequestApi {
export interface _LogPatternApi {
/** Mined log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Tokens: <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. */
pattern: string
- /** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — scale by `total_count / scanned_count` to estimate. */
+ /** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — prefer `estimated_count` for display. */
count: number
+ /** Estimated occurrences across the full window, extrapolated from the sample (`count / scanned_count * total_count`). Equals `count` when the window was not sampled. */
+ estimated_count: number
/** Share of the sampled log volume this pattern represents (0–100). */
volume_share_pct: number
- /** Sampled occurrences at severity "error" or "fatal". */
+ /** Sampled occurrences at severity "error" or "fatal". Prefer `estimated_error_count` for display. */
error_count: number
+ /** Estimated error/fatal occurrences across the full window, extrapolated from the sample. Equals `error_count` when the window was not sampled. */
+ estimated_error_count: number
/** ISO 8601 timestamp of the earliest sampled occurrence. */
first_seen: string
/** ISO 8601 timestamp of the latest sampled occurrence. */
@@ -1096,8 +1100,10 @@ export interface _LogsPatternsResponseApi {
scanned_count: number
/** Total log rows matching the filters in the window, before sampling. Use with `scanned_count` to scale per-pattern counts when `sampled` is true. */
total_count: number
- /** True when the window held more rows than the sample cap, so patterns were mined from an evenly-distributed random sample rather than every matching row. */
+ /** True when the window held more rows than the sample cap, so patterns were mined from a deterministic, evenly-distributed sample rather than every matching row. */
sampled: boolean
+ /** Share of the window's log rows that were eligible for sampling (0–100). Below 100, the scan was bounded to evenly-spaced time slices across the window to keep the query within its execution budget; rows outside the slices could not appear in the sample. */
+ sample_coverage_pct: number
}
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fa92178cc23d..6456da9b5fb9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54032,12 +54032,16 @@ export namespace Schemas {
export interface _LogPattern {
/** Mined log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Tokens: <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. */
pattern: string;
- /** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — scale by `total_count / scanned_count` to estimate. */
+ /** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — prefer `estimated_count` for display. */
count: number;
+ /** Estimated occurrences across the full window, extrapolated from the sample (`count / scanned_count * total_count`). Equals `count` when the window was not sampled. */
+ estimated_count: number;
/** Share of the sampled log volume this pattern represents (0–100). */
volume_share_pct: number;
- /** Sampled occurrences at severity "error" or "fatal". */
+ /** Sampled occurrences at severity "error" or "fatal". Prefer `estimated_error_count` for display. */
error_count: number;
+ /** Estimated error/fatal occurrences across the full window, extrapolated from the sample. Equals `error_count` when the window was not sampled. */
+ estimated_error_count: number;
/** ISO 8601 timestamp of the earliest sampled occurrence. */
first_seen: string;
/** ISO 8601 timestamp of the latest sampled occurrence. */
@@ -54255,8 +54259,10 @@ export namespace Schemas {
scanned_count: number;
/** Total log rows matching the filters in the window, before sampling. Use with `scanned_count` to scale per-pattern counts when `sampled` is true. */
total_count: number;
- /** True when the window held more rows than the sample cap, so patterns were mined from an evenly-distributed random sample rather than every matching row. */
+ /** True when the window held more rows than the sample cap, so patterns were mined from a deterministic, evenly-distributed sample rather than every matching row. */
sampled: boolean;
+ /** Share of the window's log rows that were eligible for sampling (0–100). Below 100, the scan was bounded to evenly-spaced time slices across the window to keep the query within its execution budget; rows outside the slices could not appear in the sample. */
+ sample_coverage_pct: number;
}
export interface _LogsQueryBody {