: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(logs): add a replay harness for pattern miner changes (#83118)
Jon McCallumd097230f546c
diff --git a/.gitignore b/.gitignoreindex 95d2985b95a1..8bd2298c21be 100644--- a/.gitignore+++ b/.gitignore@@ -229,3 +229,7 @@ rust/cohort-stream-processor/cohort-store/# Redis persistence snapshot dropped by a locally running redis-serverdump.rdb++# Log corpora captured for the pattern replay harness. These hold real log bodies —+# addresses, hostnames, request ids, user agents — and this repository is public.+corpora/diff --git a/products/logs/backend/pattern_replay.py b/products/logs/backend/pattern_replay.pynew file mode 100644index 000000000000..c79c4d71acda--- /dev/null+++ b/products/logs/backend/pattern_replay.py@@ -0,0 +1,304 @@+"""Replay a fixed corpus of log bodies through the miner and measure the result.++Masking and truncation interact: every masking change shifts string lengths, which moves+the truncation cut point. A miner change therefore cannot be judged by reading its output.+It needs the same corpus measured before and after, which is what this module does.++Compare two tunings in one run:++ python -m products.logs.backend.pattern_replay corpora/edge.jsonl --compare truncate=1024++Compare a code change across two runs, one per branch:++ python -m products.logs.backend.pattern_replay corpora/edge.jsonl --save before.json+ python -m products.logs.backend.pattern_replay corpora/edge.jsonl --baseline before.json++A corpus is one JSON object per line, each with at least a `body`; `service_name`,+`severity_text`, and `timestamp` are optional. Capture one per service from query-logs rows+and keep it under `corpora/`, which is gitignored, because a corpus holds real log bodies+and this repository is public. `test/fixtures/pattern_replay_sample.jsonl` is invented data,+small enough to smoke-test the command but too small to measure a change against.+"""++import os+import json+import argparse+import datetime as dt+from collections import defaultdict+from dataclasses import asdict, fields+from pathlib import Path+from typing import get_type_hints++from posthog.dataclasses import frozen++from products.logs.backend.log_patterns import LogSample, _env, mine_patterns++# Mining reads timestamps only to report first/last seen, which the harness does not score.+# A corpus may therefore omit them, and every such row shares this stamp.+_UNDATED = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)++# mine_patterns defaults to the 200 rows the API renders. Measuring through that cap would+# read a 400-template corpus as 200 and hide exactly the fragmentation this tool exists to+# find, so the harness asks for every cluster Drain kept.+_UNCAPPED = 1_000_000+++# One home for the env var names, so reading the tuning and overriding it from the command+# line cannot drift apart.+_ENV_VARS = {+ "truncate": "LOGS_PATTERNS_BODY_TRUNCATE",+ "sim_th": "LOGS_PATTERNS_SIM_TH",+ "depth": "LOGS_PATTERNS_DEPTH",+ "max_clusters": "LOGS_PATTERNS_MAX_CLUSTERS",+}+++@frozen+class ReplayConfig:+ truncate: int+ sim_th: float+ depth: int+ max_clusters: int++ @classmethod+ def from_env(cls) -> "ReplayConfig":+ # Read through the miner's own _env, so a value it rejects and defaults is recorded+ # here as the default it actually mined with, not the string the environment held.+ # The default literals below still mirror the ones mine_patterns passes to _env, and+ # nothing binds the two. Change a default there without changing it here and every+ # report misstates the tuning it measured, while diff_reports sees two matching+ # configs and stays quiet, which is the one moment its warning is worth most.+ return cls(+ truncate=_env(_ENV_VARS["truncate"], 512, int),+ sim_th=_env(_ENV_VARS["sim_th"], 0.4, float),+ depth=_env(_ENV_VARS["depth"], 4, int),+ max_clusters=_env(_ENV_VARS["max_clusters"], 1000, int),+ )+++@frozen+class ServiceReport:+ service_name: str+ sample_count: int+ template_count: int+ prefix_duplicate_count: int+++@frozen+class ReplayReport:+ sample_count: int+ template_count: int+ prefix_duplicate_count: int+ config: ReplayConfig+ # Each service mined alone, alongside the blended figures above. Production mines every+ # service together, so the blended number is the one that ships. Fragmentation is a+ # property of one service's body shape, and blending buries which service owns it.+ services: tuple[ServiceReport, ...] = ()+++@frozen+class ReplayDiff:+ template_delta: int+ prefix_duplicate_delta: int+ # Config keys whose values differ between the two runs. Non-empty means the deltas+ # above measure the config change as much as the code change, so they answer nothing.+ config_mismatch: tuple[str, ...]+++def count_prefix_duplicates(templates: list[str]) -> int:+ """Count templates that are a strict prefix of another template.++ The headline metric. One log statement whose body is cut at a drifting offset lands in+ several clusters whose templates are prefixes of each other, so this counts how badly+ the corpus is fragmenting. Raw template count alone hides that: a change can trade+ character-level fragments for word-level ones and leave the total flat.+ """+ ordered = sorted(templates)+ # Only neighbors need comparing. If a sorts before c and is a prefix of it, anything+ # sorting between them also starts with a, so a prefix relation always shows up+ # adjacent, so no pair is missed by skipping the quadratic sweep.+ return sum(1 for a, b in zip(ordered, ordered[1:]) if b != a and b.startswith(a))+++def load_corpus(path: Path) -> list[LogSample]:+ """Read a corpus of log rows, one JSON object per line.++ Only `body` is required. Corpora are captured from real streams and are never checked+ in, so the reader stays tolerant of whatever the capture step left behind.+ """+ samples = []+ for line in path.read_text().splitlines():+ if not line.strip():+ continue+ row = json.loads(line)+ raw_timestamp = row.get("timestamp")+ samples.append(+ LogSample(+ body=row["body"],+ severity_text=row.get("severity_text", "info"),+ service_name=row.get("service_name", "unknown"),+ timestamp=dt.datetime.fromisoformat(raw_timestamp) if raw_timestamp else _UNDATED,+ )+ )+ return samples+++def _mine_templates(samples: list[LogSample]) -> list[str]:+ return [pattern.pattern for pattern in mine_patterns(samples, max_patterns=_UNCAPPED)]+++def measure(samples: list[LogSample]) -> ReplayReport:+ """Mine a corpus and score how badly it fragments, overall and per service."""+ by_service: dict[str, list[LogSample]] = defaultdict(list)+ for sample in samples:+ by_service[sample.service_name].append(sample)++ services = []+ for name, owned in sorted(by_service.items()):+ owned_templates = _mine_templates(owned)+ services.append(+ ServiceReport(+ service_name=name,+ sample_count=len(owned),+ template_count=len(owned_templates),+ prefix_duplicate_count=count_prefix_duplicates(owned_templates),+ )+ )++ templates = _mine_templates(samples)+ return ReplayReport(+ sample_count=len(samples),+ template_count=len(templates),+ prefix_duplicate_count=count_prefix_duplicates(templates),+ config=ReplayConfig.from_env(),+ services=tuple(services),+ )+++def diff_reports(baseline: ReplayReport, candidate: ReplayReport) -> ReplayDiff:+ """Compare two runs, refusing to imply a delta the numbers cannot support.++ A miner change is judged by re-running the same corpus, so the tuning has to be held+ still across both runs. When it was not, the deltas still compute, they just no longer+ isolate the change, which is why the mismatch travels with them instead of being dropped.+ """+ mismatch = tuple(+ field.name+ for field in fields(ReplayConfig)+ if getattr(baseline.config, field.name) != getattr(candidate.config, field.name)+ )+ return ReplayDiff(+ template_delta=candidate.template_count - baseline.template_count,+ prefix_duplicate_delta=candidate.prefix_duplicate_count - baseline.prefix_duplicate_count,+ config_mismatch=mismatch,+ )+++def _measure_with(samples: list[LogSample], overrides: dict[str, str]) -> ReplayReport:+ # mine_patterns reads its tuning from the environment, so a second tuning means a second+ # environment. Restored afterwards, so the run that follows reports its own config.+ previous = {name: os.environ.get(name) for name in overrides}+ os.environ.update(overrides)+ try:+ return measure(samples)+ finally:+ for name, value in previous.items():+ if value is None:+ os.environ.pop(name, None)+ else:+ os.environ[name] = value+++def _parse_overrides(pairs: list[str]) -> dict[str, str]:+ """Turn `key=value` arguments into environment overrides, rejecting any that would not apply.++ _env falls back to its default whenever a value fails to parse, so an unusable override+ mines at the default and reports the default. Both runs then agree, config_mismatch stays+ empty, and the diff reads as a real "no change" answer to a comparison never made. Refuse+ the value here, where the mistake is still visible.+ """+ parsers = get_type_hints(ReplayConfig)+ overrides = {}+ for pair in pairs:+ key, assigned, value = pair.partition("=")+ if key not in _ENV_VARS:+ raise SystemExit(f"unknown config key {key!r}, expected one of {', '.join(_ENV_VARS)}")+ if not assigned or not value:+ raise SystemExit(f"config key {key!r} needs a value, written as {key}=<value>")+ try:+ parsers[key](value)+ except ValueError:+ raise SystemExit(f"config key {key!r} needs {parsers[key].__name__}, got {value!r}")+ overrides[_ENV_VARS[key]] = value+ return overrides+++def _format_report(label: str, report: ReplayReport) -> str:+ config = " ".join(f"{field.name}={getattr(report.config, field.name)}" for field in fields(ReplayConfig))+ lines = [+ f"{label}: {report.template_count} templates, "+ f"{report.prefix_duplicate_count} prefix-duplicates, "+ f"from {report.sample_count} bodies",+ f" config: {config}",+ ]+ lines.extend(+ f" {service.service_name}: {service.template_count} templates, "+ f"{service.prefix_duplicate_count} prefix-duplicates, from {service.sample_count} bodies"+ for service in report.services+ )+ return "\n".join(lines)+++def _format_diff(diff: ReplayDiff) -> str:+ lines = [+ f"diff: {diff.template_delta:+d} templates, {diff.prefix_duplicate_delta:+d} prefix-duplicates",+ ]+ if diff.config_mismatch:+ lines.append(+ f" WARNING: {', '.join(diff.config_mismatch)} differ between the runs, "+ "so these deltas do not isolate the code change"+ )+ return "\n".join(lines)+++def main(argv: list[str] | None = None) -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("corpus", type=Path, help="JSONL file of log rows")+ parser.add_argument(+ "--compare",+ metavar="KEY=VALUE",+ action="append",+ default=[],+ help="mine a second time with these tuning overrides and diff the two",+ )+ parser.add_argument("--save", type=Path, help="write this run's report for a later --baseline")+ parser.add_argument("--baseline", type=Path, help="diff this run against a saved report")+ args = parser.parse_args(argv)++ samples = load_corpus(args.corpus)+ report = measure(samples)+ print(_format_report("current", report))++ if args.compare:+ candidate = _measure_with(samples, _parse_overrides(args.compare))+ print(_format_report("compared", candidate))+ print(_format_diff(diff_reports(report, candidate)))++ if args.baseline:+ saved = json.loads(args.baseline.read_text())+ baseline = ReplayReport(+ sample_count=saved["sample_count"],+ template_count=saved["template_count"],+ prefix_duplicate_count=saved["prefix_duplicate_count"],+ config=ReplayConfig(**saved["config"]),+ services=tuple(ServiceReport(**service) for service in saved.get("services", ())),+ )+ print(_format_report("baseline", baseline))+ print(_format_diff(diff_reports(baseline, report)))++ if args.save:+ args.save.write_text(json.dumps(asdict(report), indent=2))+++if __name__ == "__main__":+ main()diff --git a/products/logs/backend/test/fixtures/pattern_replay_sample.jsonl b/products/logs/backend/test/fixtures/pattern_replay_sample.jsonlnew file mode 100644index 000000000000..e26c5d66cdcc--- /dev/null+++ b/products/logs/backend/test/fixtures/pattern_replay_sample.jsonl@@ -0,0 +1,36 @@+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:00:00.000Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.0:8080\",\"downstream_remote_address\":\"203.0.113.0:40000\",\"upstream_host\":\"198.51.100.0:8080\",\"duration\":0,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000000\",\"response_code\":503,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.0,198.51.100.0\",\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:01:07.001Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.1:8080\",\"downstream_remote_address\":\"203.0.113.1:40001\",\"upstream_host\":\"198.51.100.3:8080\",\"duration\":13,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000001\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.1,198.51.100.1\",\"user_agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:02:14.002Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.2:8080\",\"downstream_remote_address\":\"203.0.113.2:40002\",\"upstream_host\":\"198.51.100.6:8080\",\"duration\":26,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000002\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.2,198.51.100.2\",\"user_agent\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:03:21.003Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.3:8080\",\"downstream_remote_address\":\"203.0.113.3:40003\",\"upstream_host\":\"198.51.100.9:8080\",\"duration\":39,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000003\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.3,198.51.100.3\",\"user_agent\":\"checkout-sdk-python/3.4.1\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:04:28.004Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.4:8080\",\"downstream_remote_address\":\"203.0.113.4:40004\",\"upstream_host\":\"198.51.100.12:8080\",\"duration\":52,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000004\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.4,198.51.100.4\",\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:05:35.005Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.5:8080\",\"downstream_remote_address\":\"203.0.113.5:40005\",\"upstream_host\":\"198.51.100.15:8080\",\"duration\":65,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000005\",\"response_code\":503,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.5,198.51.100.5\",\"user_agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:06:42.006Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.6:8080\",\"downstream_remote_address\":\"203.0.113.6:40006\",\"upstream_host\":\"198.51.100.18:8080\",\"duration\":78,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000006\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.6,198.51.100.6\",\"user_agent\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:07:49.007Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.7:8080\",\"downstream_remote_address\":\"203.0.113.7:40007\",\"upstream_host\":\"198.51.100.21:8080\",\"duration\":91,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000007\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.7,198.51.100.0\",\"user_agent\":\"checkout-sdk-python/3.4.1\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:08:56.008Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.8:8080\",\"downstream_remote_address\":\"203.0.113.8:40008\",\"upstream_host\":\"198.51.100.24:8080\",\"duration\":104,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000008\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.8,198.51.100.1\",\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:09:03.009Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.9:8080\",\"downstream_remote_address\":\"203.0.113.9:40009\",\"upstream_host\":\"198.51.100.27:8080\",\"duration\":117,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000009\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.9,198.51.100.2\",\"user_agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:10:10.010Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.10:8080\",\"downstream_remote_address\":\"203.0.113.10:40010\",\"upstream_host\":\"198.51.100.30:8080\",\"duration\":130,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000010\",\"response_code\":503,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.10,198.51.100.3\",\"user_agent\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:11:17.011Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.11:8080\",\"downstream_remote_address\":\"203.0.113.11:40011\",\"upstream_host\":\"198.51.100.33:8080\",\"duration\":143,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000011\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.11,198.51.100.4\",\"user_agent\":\"checkout-sdk-python/3.4.1\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:12:24.012Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.12:8080\",\"downstream_remote_address\":\"203.0.113.12:40012\",\"upstream_host\":\"198.51.100.36:8080\",\"duration\":156,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000012\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.12,198.51.100.5\",\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:13:31.013Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.13:8080\",\"downstream_remote_address\":\"203.0.113.13:40013\",\"upstream_host\":\"198.51.100.39:8080\",\"duration\":169,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000013\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.13,198.51.100.6\",\"user_agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:14:38.014Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.14:8080\",\"downstream_remote_address\":\"203.0.113.14:40014\",\"upstream_host\":\"198.51.100.42:8080\",\"duration\":182,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000014\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.14,198.51.100.0\",\"user_agent\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:15:45.015Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.15:8080\",\"downstream_remote_address\":\"203.0.113.15:40015\",\"upstream_host\":\"198.51.100.45:8080\",\"duration\":195,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000015\",\"response_code\":503,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.15,198.51.100.1\",\"user_agent\":\"checkout-sdk-python/3.4.1\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:16:52.016Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.16:8080\",\"downstream_remote_address\":\"203.0.113.16:40016\",\"upstream_host\":\"198.51.100.48:8080\",\"duration\":208,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000016\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.16,198.51.100.2\",\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:17:59.017Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.17:8080\",\"downstream_remote_address\":\"203.0.113.17:40017\",\"upstream_host\":\"198.51.100.51:8080\",\"duration\":221,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000017\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.17,198.51.100.3\",\"user_agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:18:06.018Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.18:8080\",\"downstream_remote_address\":\"203.0.113.18:40018\",\"upstream_host\":\"198.51.100.54:8080\",\"duration\":234,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000018\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.18,198.51.100.4\",\"user_agent\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:19:13.019Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.19:8080\",\"downstream_remote_address\":\"203.0.113.19:40019\",\"upstream_host\":\"198.51.100.57:8080\",\"duration\":247,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000019\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.19,198.51.100.5\",\"user_agent\":\"checkout-sdk-python/3.4.1\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:20:20.020Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.20:8080\",\"downstream_remote_address\":\"203.0.113.20:40020\",\"upstream_host\":\"198.51.100.60:8080\",\"duration\":260,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000020\",\"response_code\":503,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.20,198.51.100.6\",\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:21:27.021Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.21:8080\",\"downstream_remote_address\":\"203.0.113.21:40021\",\"upstream_host\":\"198.51.100.63:8080\",\"duration\":273,\"method\":\"POST\",\"path\":\"/v1/orders/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000021\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.21,198.51.100.0\",\"user_agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:22:34.022Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.22:8080\",\"downstream_remote_address\":\"203.0.113.22:40022\",\"upstream_host\":\"198.51.100.66:8080\",\"duration\":286,\"method\":\"POST\",\"path\":\"/v1/orders?expand=true&limit=25\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000022\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.22,198.51.100.1\",\"user_agent\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\"}"}+{"service_name": "edge-proxy", "severity_text": "info", "body": "{\"@timestamp\":\"2026-08-14T09:23:41.023Z\",\"authority\":\"api.example.com\",\"downstream_local_address\":\"198.51.100.23:8080\",\"downstream_remote_address\":\"203.0.113.23:40023\",\"upstream_host\":\"198.51.100.69:8080\",\"duration\":299,\"method\":\"POST\",\"path\":\"/v1/carts/\",\"protocol\":\"HTTP/1.1\",\"request_id\":\"00000000-0000-4000-8000-000000000023\",\"response_code\":200,\"response_code_details\":\"via_upstream\",\"upstream_cluster\":\"example_orders_service_8080\",\"x_forwarded_for\":\"203.0.113.23,198.51.100.2\",\"user_agent\":\"checkout-sdk-python/3.4.1\"}"}+{"service_name": "orders-worker", "severity_text": "error", "body": "ts=2026-08-14T09:00:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000000 duration_ms=0.0 attempt=0"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:01:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000001 duration_ms=3.1 attempt=1"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:02:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000002 duration_ms=6.2 attempt=2"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:03:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000003 duration_ms=9.3 attempt=0"}+{"service_name": "orders-worker", "severity_text": "error", "body": "ts=2026-08-14T09:04:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000004 duration_ms=12.4 attempt=1"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:05:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000005 duration_ms=15.5 attempt=2"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:06:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000006 duration_ms=18.6 attempt=0"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:07:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000007 duration_ms=21.7 attempt=1"}+{"service_name": "orders-worker", "severity_text": "error", "body": "ts=2026-08-14T09:08:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000008 duration_ms=24.8 attempt=2"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:09:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000009 duration_ms=27.9 attempt=0"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:10:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000010 duration_ms=30.0 attempt=1"}+{"service_name": "orders-worker", "severity_text": "info", "body": "ts=2026-08-14T09:11:00Z level=info msg=\"order settled\" order_id=00000000-0000-4000-8000-000000000011 duration_ms=33.1 attempt=2"}diff --git a/products/logs/backend/test/test_pattern_replay.py b/products/logs/backend/test/test_pattern_replay.pynew file mode 100644index 000000000000..4175d81b595f--- /dev/null+++ b/products/logs/backend/test/test_pattern_replay.py@@ -0,0 +1,143 @@+import json+import datetime as dt+import tempfile+from dataclasses import replace+from pathlib import Path++from unittest import TestCase++from parameterized import parameterized++from products.logs.backend.log_patterns import LogSample+from products.logs.backend.pattern_replay import (+ ReplayConfig,+ ReplayReport,+ count_prefix_duplicates,+ diff_reports,+ load_corpus,+ main,+ measure,+)++_T0 = dt.datetime(2026, 8, 14, 12, 0, tzinfo=dt.UTC)+_SAMPLE_CORPUS = Path(__file__).parent / "fixtures" / "pattern_replay_sample.jsonl"+++def _sample(body: str, service: str = "svc") -> LogSample:+ return LogSample(body=body, severity_text="info", service_name=service, timestamp=_T0)+++_BASE_CONFIG = ReplayConfig(truncate=512, sim_th=0.4, depth=4, max_clusters=1000)+++def _report(templates: int, prefix_dupes: int, config: ReplayConfig = _BASE_CONFIG) -> ReplayReport:+ return ReplayReport(+ sample_count=1000,+ template_count=templates,+ prefix_duplicate_count=prefix_dupes,+ config=config,+ )+++class TestPatternReplay(TestCase):+ @parameterized.expand(+ [+ ("a lone template is not its own prefix", ["a b c"], 0),+ ("equal templates are not strict prefixes", ["a b", "a b"], 0),+ ("the prefix is counted, not its extensions", ["x", "xa", "xb"], 1),+ ("every link in a chain counts once", ["x", "xa", "xab"], 2),+ ("unrelated templates never match", ["alpha", "beta"], 0),+ ("an empty corpus counts nothing", [], 0),+ ]+ )+ def test_count_prefix_duplicates(self, _name: str, templates: list[str], expected: int) -> None:+ self.assertEqual(count_prefix_duplicates(templates), expected)++ def test_measure_counts_mined_templates_not_raw_bodies(self) -> None:+ samples = [_sample(f"connected to 10.0.0.{i} in {i} ms") for i in range(20)]++ report = measure(samples)++ self.assertEqual(report.sample_count, 20)+ self.assertEqual(report.template_count, 1)++ def test_measure_sees_past_the_api_display_cap(self) -> None:+ # Unique literal tokens and a spread of token counts, so Drain cannot merge these+ # into each other and the corpus really does hold more than the 200-row display cap.+ samples = [_sample(" ".join(f"tok{i}x{k}" for k in range(3 + i % 40))) for i in range(320)]++ report = measure(samples)++ self.assertGreater(report.template_count, 200)++ def test_measure_scores_each_service_on_its_own_bodies(self) -> None:+ one_shape = [_sample(f"cache hit for key 10.0.0.{i}", service="alpha") for i in range(10)]+ many_shapes = [_sample(" ".join(f"w{i}x{k}" for k in range(3 + i % 12)), service="beta") for i in range(10)]++ report = measure(one_shape + many_shapes)++ by_name = {service.service_name: service for service in report.services}+ self.assertEqual(by_name["alpha"].sample_count, 10)+ self.assertEqual(by_name["alpha"].template_count, 1)+ self.assertGreater(by_name["beta"].template_count, 1)++ def test_measure_records_the_config_it_ran_under(self) -> None:+ report = measure([_sample("anything at all")])++ self.assertEqual(report.config, _BASE_CONFIG)++ def test_diff_subtracts_candidate_from_baseline(self) -> None:+ diff = diff_reports(_report(templates=426, prefix_dupes=106), _report(templates=263, prefix_dupes=35))++ self.assertEqual(diff.config_mismatch, ())+ self.assertEqual(diff.template_delta, -163)+ self.assertEqual(diff.prefix_duplicate_delta, -71)++ @parameterized.expand(+ [+ ("truncate", replace(_BASE_CONFIG, truncate=1024)),+ ("sim_th", replace(_BASE_CONFIG, sim_th=0.6)),+ ("depth", replace(_BASE_CONFIG, depth=6)),+ ("max_clusters", replace(_BASE_CONFIG, max_clusters=5000)),+ ]+ )+ def test_diff_flags_reports_mined_under_different_config(self, field: str, changed: ReplayConfig) -> None:+ baseline = _report(templates=426, prefix_dupes=106)+ candidate = _report(templates=263, prefix_dupes=35, config=changed)++ diff = diff_reports(baseline, candidate)++ self.assertEqual(diff.config_mismatch, (field,))++ def test_load_corpus_keeps_bodies_whole(self) -> None:+ multiline = 'Traceback:\n File "app.py", line 3\n raise ValueError("boom")'+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "corpus.jsonl"+ path.write_text(+ json.dumps({"body": multiline, "service_name": "checkout"})+ + "\n\n"+ + json.dumps({"body": "plain line"})+ + "\n"+ )++ samples = load_corpus(path)++ self.assertEqual([s.body for s in samples], [multiline, "plain line"])+ self.assertEqual(samples[0].service_name, "checkout")++ def test_cli_runs_without_crashing(self) -> None:+ main([str(_SAMPLE_CORPUS), "--compare", "truncate=1024"])++ @parameterized.expand(+ [+ ("no value at all", "truncate"),+ ("an empty value", "truncate="),+ ("a word where a number belongs", "truncate=abc"),+ ("a fraction for a whole-number knob", "truncate=1.5"),+ ("a word where a fraction belongs", "sim_th=abc"),+ ("a knob that does not exist", "nonsense=1"),+ ]+ )+ def test_cli_refuses_an_override_it_cannot_apply(self, _name: str, pair: str) -> None:+ with self.assertRaises(SystemExit):+ main([str(_SAMPLE_CORPUS), "--compare", pair])diff --git a/products/ruff.toml b/products/ruff.tomlindex 97445bbfd59a..4389ba9dc1c1 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -18,6 +18,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]# CLI; prints its report (T201)."data_catalog/scripts/offline_governance_experiment.py" = ["T201"]+"logs/backend/pattern_replay.py" = ["T201"]# Temporarily exempted — too many violations to fix in one pass.# Run: ruff check products/<name>/backend --select ANN --statistics