: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
feat(logs): add log pattern mining helper (vendored drain3) (#66080)
Jon McCallum90f9da433075
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pynew file mode 100644index 000000000000..8d1a28397f49--- /dev/null+++ b/products/logs/backend/log_patterns.py@@ -0,0 +1,166 @@+import os+import re+import datetime as dt+from collections.abc import Callable+from dataclasses import dataclass, field+from typing import TypeVar++from products.logs.backend.vendor.drain3 import Drain, LogMasker, MaskingInstruction++_ERROR_SEVERITIES = {"error", "fatal"}++# Masking collapses high-cardinality variable tokens into named placeholders before+# clustering, so templates stay readable ("<ip>", "<num>") instead of fragmenting into+# one cluster per distinct value. Order matters — Drain applies these in sequence, so+# more-specific patterns (uuid, ip, hex) run before the catch-all number mask.+_MASKING_INSTRUCTIONS = [+ MaskingInstruction(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b", "uuid"),+ MaskingInstruction(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "ip"),+ MaskingInstruction(r"\b0x[0-9a-fA-F]+\b", "hex"),+ MaskingInstruction(r"\b[0-9a-fA-F]{16,}\b", "hex"),+ MaskingInstruction(r"\b\d+\b", "num"),+]++_WHITESPACE_RE = re.compile(r"\s+")+++_T = TypeVar("_T", int, float)+++def _env(name: str, default: _T, cast: Callable[[str], _T]) -> _T:+ raw = os.environ.get(name)+ if raw is None:+ return default+ try:+ return cast(raw)+ except ValueError:+ return default+++@dataclass(frozen=True)+class LogSample:+ body: str+ severity_text: str+ service_name: str+ timestamp: dt.datetime+++@dataclass+class MinedPattern:+ pattern: str+ count: int+ volume_share_pct: float+ error_count: int+ first_seen: dt.datetime+ last_seen: dt.datetime+ examples: list[str]+ services: list[str]+++@dataclass+class _Accumulator:+ template: str+ first_seen: dt.datetime+ last_seen: dt.datetime+ count: int = 0+ error_count: int = 0+ examples: list[str] = field(default_factory=list)+ services: list[str] = field(default_factory=list)+++def _prepare_body(body: str, truncate: int) -> str:+ # Collapse newlines / whitespace runs so multi-line bodies (stack traces) mine as a+ # single line, then bound length to keep Drain's parse tree and memory in check.+ return _WHITESPACE_RE.sub(" ", body).strip()[:truncate]+++def _build_miner(sim_th: float, depth: int, max_clusters: int) -> tuple[LogMasker, Drain]:+ masker = LogMasker(list(_MASKING_INSTRUCTIONS), "<", ">")+ drain = Drain(+ sim_th=sim_th,+ depth=depth,+ max_clusters=max_clusters,+ param_str="<*>",+ parametrize_numeric_tokens=True,+ )+ return masker, drain+++def mine_patterns(+ samples: list[LogSample],+ *,+ max_patterns: int | None = None,+ max_examples: int | None = None,+ max_services: int | None = None,+) -> list[MinedPattern]:+ """Cluster log bodies into templates via Drain3, aggregated per cluster.++ Pure function — no ClickHouse or Django. The caller (query runner) is responsible+ for sampling and for the `scanned_count` / `sampled` metadata.++ Tuning is split deliberately: the output-shape caps (`max_patterns`, `max_examples`,+ `max_services`) are exposed as kwargs so callers and tests can override them per call,+ while the mining params (`LOGS_PATTERNS_BODY_TRUNCATE`, `_SIM_TH`, `_DEPTH`,+ `_MAX_CLUSTERS`) are env-only so ops can retune clustering without a deploy. Each kwarg+ falls back to its `LOGS_PATTERNS_*` env var, then a default.+ """+ if not samples:+ return []++ max_patterns = max_patterns if max_patterns is not None else _env("LOGS_PATTERNS_MAX_PATTERNS", 200, int)+ max_examples = max_examples if max_examples is not None else _env("LOGS_PATTERNS_MAX_EXAMPLES", 3, int)+ max_services = max_services if max_services is not None else _env("LOGS_PATTERNS_MAX_SERVICES", 4, int)+ truncate = _env("LOGS_PATTERNS_BODY_TRUNCATE", 512, int)+ sim_th = _env("LOGS_PATTERNS_SIM_TH", 0.4, float)+ depth = _env("LOGS_PATTERNS_DEPTH", 4, int)+ max_clusters = _env("LOGS_PATTERNS_MAX_CLUSTERS", 1000, int)++ masker, drain = _build_miner(sim_th, depth, max_clusters)+ accumulators: dict[int, _Accumulator] = {}++ for sample in samples:+ prepared = _prepare_body(sample.body, truncate)+ cluster, _change_type = drain.add_log_message(masker.mask(prepared))+ cluster_id = cluster.cluster_id++ acc = accumulators.get(cluster_id)+ if acc is None:+ acc = _Accumulator(+ template=cluster.get_template(),+ first_seen=sample.timestamp,+ last_seen=sample.timestamp,+ )+ accumulators[cluster_id] = acc+ else:+ # Keep the most-evolved template — Drain refines it as more rows merge in.+ acc.template = cluster.get_template()+ if sample.timestamp < acc.first_seen:+ acc.first_seen = sample.timestamp+ if sample.timestamp > acc.last_seen:+ acc.last_seen = sample.timestamp++ acc.count += 1+ if sample.severity_text.lower() in _ERROR_SEVERITIES:+ acc.error_count += 1+ if len(acc.examples) < max_examples and prepared not in acc.examples:+ acc.examples.append(prepared)+ if sample.service_name not in acc.services and len(acc.services) < max_services:+ acc.services.append(sample.service_name)++ total = len(samples)+ patterns = [+ MinedPattern(+ pattern=acc.template,+ count=acc.count,+ volume_share_pct=round(acc.count / total * 100, 2),+ error_count=acc.error_count,+ first_seen=acc.first_seen,+ last_seen=acc.last_seen,+ examples=acc.examples,+ services=acc.services,+ )+ for acc in accumulators.values()+ ]+ # Most frequent first; tie-break on template for deterministic ordering.+ patterns.sort(key=lambda p: (-p.count, p.pattern))+ return patterns[:max_patterns]diff --git a/products/logs/backend/test/test_log_patterns.py b/products/logs/backend/test/test_log_patterns.pynew file mode 100644index 000000000000..110cf39b6d8b--- /dev/null+++ b/products/logs/backend/test/test_log_patterns.py@@ -0,0 +1,136 @@+import datetime as dt++from unittest import TestCase++from parameterized import parameterized++from products.logs.backend.log_patterns import LogSample, mine_patterns+++def _sample(+ body: str,+ severity: str = "info",+ service: str = "api",+ ts: dt.datetime | None = None,+) -> LogSample:+ return LogSample(+ body=body,+ severity_text=severity,+ service_name=service,+ timestamp=ts or dt.datetime(2026, 6, 23, 12, 0, 0, tzinfo=dt.UTC),+ )+++class TestMinePatterns(TestCase):+ def test_merges_messages_differing_by_one_word_into_one_template(self) -> None:+ samples = [+ _sample("User alice not found"),+ _sample("User bob not found"),+ _sample("User carol not found"),+ ]++ patterns = mine_patterns(samples)++ assert len(patterns) == 1+ assert patterns[0].count == 3+ assert "User" in patterns[0].pattern+ assert "not found" in patterns[0].pattern+ # the varying token is collapsed to a wildcard, not preserved verbatim+ assert "alice" not in patterns[0].pattern+ assert "<*>" in patterns[0].pattern++ @parameterized.expand(+ [+ ("numbers", ["Request 123 took 5 ms", "Request 456 took 9 ms"], "<num>", "123"),+ ("ipv4", ["GET from 10.0.0.1", "GET from 192.168.1.1"], "<ip>", "10.0.0.1"),+ (+ "uuid",+ [+ "trace 550e8400-e29b-41d4-a716-446655440000 start",+ "trace 550e8400-e29b-41d4-a716-446655440001 start",+ ],+ "<uuid>",+ "446655440000",+ ),+ ]+ )+ def test_masking_collapses_variable_tokens(+ self, _name: str, lines: list[str], expected_token: str, raw_token: str+ ) -> None:+ patterns = mine_patterns([_sample(line) for line in lines])++ assert len(patterns) == 1+ assert patterns[0].count == 2+ assert expected_token in patterns[0].pattern+ assert raw_token not in patterns[0].pattern++ def test_error_count_includes_only_error_and_fatal(self) -> None:+ samples = [+ _sample("db connection dropped", severity="error"),+ _sample("db connection dropped", severity="fatal"),+ _sample("db connection dropped", severity="info"),+ _sample("db connection dropped", severity="warn"),+ ]++ patterns = mine_patterns(samples)++ assert len(patterns) == 1+ assert patterns[0].count == 4+ assert patterns[0].error_count == 2++ def test_orders_by_count_desc_with_volume_share(self) -> None:+ samples = [_sample("alpha event happened")] * 3 + [_sample("a totally separate message line")]++ patterns = mine_patterns(samples)++ assert [p.count for p in patterns] == [3, 1]+ assert patterns[0].volume_share_pct == 75.0+ assert patterns[1].volume_share_pct == 25.0++ def test_services_are_distinct_and_capped(self) -> None:+ samples = [_sample("same templated message", service=f"svc{i % 3}") for i in range(9)]++ patterns = mine_patterns(samples, max_services=2)++ assert patterns[0].count == 9+ assert patterns[0].services == ["svc0", "svc1"]++ def test_examples_are_distinct_and_capped(self) -> None:+ samples = [_sample(f"error code {i}") for i in range(5)]++ patterns = mine_patterns(samples, max_examples=2)++ # all five cluster together (the number is masked), but only two examples are kept+ assert patterns[0].count == 5+ assert patterns[0].examples == ["error code 0", "error code 1"]++ def test_long_bodies_are_truncated_before_mining(self) -> None:+ patterns = mine_patterns([_sample("x" * 1000)])++ assert len(patterns[0].examples[0]) == 512++ def test_first_and_last_seen_span_the_cluster(self) -> None:+ earliest = dt.datetime(2026, 6, 23, 12, 0, 0, tzinfo=dt.UTC)+ middle = dt.datetime(2026, 6, 23, 12, 5, 0, tzinfo=dt.UTC)+ latest = dt.datetime(2026, 6, 23, 12, 10, 0, tzinfo=dt.UTC)+ samples = [+ _sample("steady message", ts=middle),+ _sample("steady message", ts=latest),+ _sample("steady message", ts=earliest),+ ]++ patterns = mine_patterns(samples)++ assert patterns[0].first_seen == earliest+ assert patterns[0].last_seen == latest++ def test_max_patterns_caps_returned_clusters(self) -> None:+ # distinct token-lengths force distinct clusters+ samples = [_sample(" ".join(["tok"] * n)) for n in range(1, 6)]++ patterns = mine_patterns(samples, max_patterns=2)++ assert len(patterns) == 2++ def test_empty_input_returns_empty(self) -> None:+ assert mine_patterns([]) == []diff --git a/products/logs/backend/vendor/__init__.py b/products/logs/backend/vendor/__init__.pynew file mode 100644index 000000000000..cc67f83c40cf--- /dev/null+++ b/products/logs/backend/vendor/__init__.py@@ -0,0 +1,2 @@+# Vendored third-party code, organized one subdirectory per library.+# Each file carries its own upstream attribution + license header.diff --git a/products/logs/backend/vendor/drain3/__init__.py b/products/logs/backend/vendor/drain3/__init__.pynew file mode 100644index 000000000000..17f8465f9e82--- /dev/null+++ b/products/logs/backend/vendor/drain3/__init__.py@@ -0,0 +1,11 @@+# Vendored from drain3 0.9.11 (https://github.com/IBM/Drain3). Only the in-memory mining algorithm+# is taken: drain.py + masking.py (MIT) and simple_profiler.py (Apache-2.0); each file carries its+# full upstream attribution + license header. drain3's TemplateMiner persistence wrapper is+# intentionally omitted — it is the sole importer of jsonpickle (an insecure-by-design+# deserializer), and we mine at query time in memory, so Drain state is never persisted/loaded.+# Re-vendor: `pip download drain3==<v> --no-deps --no-binary :all:`, copy the three files, then+# re-apply the relative import + repo-style fixups (ruff format/fix, ty annotations).+from .drain import Drain+from .masking import LogMasker, MaskingInstruction++__all__ = ["Drain", "LogMasker", "MaskingInstruction"]diff --git a/products/logs/backend/vendor/drain3/drain.py b/products/logs/backend/vendor/drain3/drain.pynew file mode 100644index 000000000000..432671823ae5--- /dev/null+++ b/products/logs/backend/vendor/drain3/drain.py@@ -0,0 +1,449 @@+# Vendored from drain3 0.9.11 — https://github.com/IBM/Drain3+# Local changes: import made relative; ruff-formatted/fixed; ty annotation fixes.+#+# MIT License+#+# Copyright (c) 2020-2022 International Business Machines+# and the Drain3 project contributors.+#+# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:+#+# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.+#+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE.+# ruff: noqa+# mypy: ignore-errors+# SPDX-License-Identifier: MIT+# This file implements the Drain algorithm for log parsing.+# Based on https://github.com/logpai/logparser/blob/master/logparser/Drain/Drain.py by LogPAI team++from collections.abc import Sequence++from cachetools import Cache, LRUCache++from .simple_profiler import NullProfiler, Profiler+++class LogCluster:+ __slots__ = ["log_template_tokens", "cluster_id", "size"]++ def __init__(self, log_template_tokens: list, cluster_id: int):+ self.log_template_tokens = tuple(log_template_tokens)+ self.cluster_id = cluster_id+ self.size = 1++ def get_template(self):+ return " ".join(self.log_template_tokens)++ def __str__(self):+ return f"ID={str(self.cluster_id).ljust(5)} : size={str(self.size).ljust(10)}: {self.get_template()}"+++class LogClusterCache(LRUCache):+ """+ Least Recently Used (LRU) cache which allows callers to conditionally skip+ cache eviction algorithm when accessing elements.+ """++ def __missing__(self, key):+ return None++ def get(self, key):+ """+ Returns the value of the item with the specified key without updating+ the cache eviction algorithm.+ """+ return Cache.__getitem__(self, key)+++class Node:+ __slots__ = ["key_to_child_node", "cluster_ids"]++ def __init__(self):+ self.key_to_child_node: dict[str, Node] = {}+ self.cluster_ids: list[int] = []+++class Drain:+ def __init__(+ self,+ depth=4,+ sim_th=0.4,+ max_children=100,+ max_clusters=None,+ extra_delimiters=(),+ profiler: Profiler = NullProfiler(),+ param_str="<*>",+ parametrize_numeric_tokens=True,+ ):+ """+ Create a new Drain instance.++ :param depth: max depth levels of log clusters. Minimum is 2.+ For example, for depth==4, Root is considered depth level 1.+ Token count is considered depth level 2.+ First log token is considered depth level 3.+ Log clusters below first token node are considered depth level 4.+ :param sim_th: similarity threshold - if percentage of similar tokens for a log message is below this+ number, a new log cluster will be created.+ :param max_children: max number of children of an internal node+ :param max_clusters: max number of tracked clusters (unlimited by default).+ When this number is reached, model starts replacing old clusters+ with a new ones according to the LRU policy.+ :param extra_delimiters: delimiters to apply when splitting log message into words (in addition to whitespace).+ :param parametrize_numeric_tokens: whether to treat tokens that contains at least one digit+ as template parameters.+ """+ if depth < 3:+ raise ValueError("depth argument must be at least 3")++ self.log_cluster_depth = depth+ self.max_node_depth = depth - 2 # max depth of a prefix tree node, starting from zero+ self.sim_th = sim_th+ self.max_children = max_children+ self.root_node = Node()+ self.profiler = profiler+ self.extra_delimiters = extra_delimiters+ self.max_clusters = max_clusters+ self.param_str = param_str+ self.parametrize_numeric_tokens = parametrize_numeric_tokens++ # key: int, value: LogCluster+ self.id_to_cluster = {} if max_clusters is None else LogClusterCache(maxsize=max_clusters)+ self.clusters_counter = 0++ @property+ def clusters(self):+ return self.id_to_cluster.values()++ @staticmethod+ def has_numbers(s):+ return any(char.isdigit() for char in s)++ def tree_search(self, root_node: Node, tokens: list, sim_th: float, include_params: bool):++ # at first level, children are grouped by token (word) count+ token_count = len(tokens)+ cur_node = root_node.key_to_child_node.get(str(token_count))++ # no template with same token count yet+ if cur_node is None:+ return None++ # handle case of empty log string - return the single cluster in that group+ if token_count == 0:+ return self.id_to_cluster.get(cur_node.cluster_ids[0])++ # find the leaf node for this log - a path of nodes matching the first N tokens (N=tree depth)+ cur_node_depth = 1+ for token in tokens:+ # at max depth+ if cur_node_depth >= self.max_node_depth:+ break++ # this is last token+ if cur_node_depth == token_count:+ break++ key_to_child_node = cur_node.key_to_child_node+ cur_node = key_to_child_node.get(token)+ if cur_node is None: # no exact next token exist, try wildcard node+ cur_node = key_to_child_node.get(self.param_str)+ if cur_node is None: # no wildcard node exist+ return None++ cur_node_depth += 1++ # get best match among all clusters with same prefix, or None if no match is above sim_th+ cluster = self.fast_match(cur_node.cluster_ids, tokens, sim_th, include_params)+ return cluster++ def add_seq_to_prefix_tree(self, root_node, cluster: LogCluster):+ token_count = len(cluster.log_template_tokens)+ token_count_str = str(token_count)+ if token_count_str not in root_node.key_to_child_node:+ first_layer_node = Node()+ root_node.key_to_child_node[token_count_str] = first_layer_node+ else:+ first_layer_node = root_node.key_to_child_node[token_count_str]++ cur_node = first_layer_node++ # handle case of empty log string+ if token_count == 0:+ cur_node.cluster_ids = [cluster.cluster_id]+ return++ current_depth = 1+ for token in cluster.log_template_tokens:+ # if at max depth or this is last token in template - add current log cluster to the leaf node+ if current_depth >= self.max_node_depth or current_depth >= token_count:+ # clean up stale clusters before adding a new one.+ new_cluster_ids = []+ for cluster_id in cur_node.cluster_ids:+ if cluster_id in self.id_to_cluster:+ new_cluster_ids.append(cluster_id)+ new_cluster_ids.append(cluster.cluster_id)+ cur_node.cluster_ids = new_cluster_ids+ break++ # if token not matched in this layer of existing tree.+ if token not in cur_node.key_to_child_node:+ if self.parametrize_numeric_tokens and self.has_numbers(token):+ if self.param_str not in cur_node.key_to_child_node:+ new_node = Node()+ cur_node.key_to_child_node[self.param_str] = new_node+ cur_node = new_node+ else:+ cur_node = cur_node.key_to_child_node[self.param_str]++ else:+ if self.param_str in cur_node.key_to_child_node:+ if len(cur_node.key_to_child_node) < self.max_children:+ new_node = Node()+ cur_node.key_to_child_node[token] = new_node+ cur_node = new_node+ else:+ cur_node = cur_node.key_to_child_node[self.param_str]+ else:+ if len(cur_node.key_to_child_node) + 1 < self.max_children:+ new_node = Node()+ cur_node.key_to_child_node[token] = new_node+ cur_node = new_node+ elif len(cur_node.key_to_child_node) + 1 == self.max_children:+ new_node = Node()+ cur_node.key_to_child_node[self.param_str] = new_node+ cur_node = new_node+ else:+ cur_node = cur_node.key_to_child_node[self.param_str]++ # if the token is matched+ else:+ cur_node = cur_node.key_to_child_node[token]++ current_depth += 1++ # seq1 is a template, seq2 is the log to match+ def get_seq_distance(self, seq1, seq2, include_params: bool):+ assert len(seq1) == len(seq2)++ # sequences are empty - full match+ if len(seq1) == 0:+ return 1.0, 0++ sim_tokens = 0+ param_count = 0++ for token1, token2 in zip(seq1, seq2):+ if token1 == self.param_str:+ param_count += 1+ continue+ if token1 == token2:+ sim_tokens += 1++ if include_params:+ sim_tokens += param_count++ ret_val = float(sim_tokens) / len(seq1)++ return ret_val, param_count++ def fast_match(self, cluster_ids: Sequence, tokens: list, sim_th: float, include_params: bool):+ """+ Find the best match for a log message (represented as tokens) versus a list of clusters+ :param cluster_ids: List of clusters to match against (represented by their IDs)+ :param tokens: the log message, separated to tokens.+ :param sim_th: minimum required similarity threshold (None will be returned in no clusters reached it)+ :param include_params: consider tokens matched to wildcard parameters in similarity threshold.+ :return: Best match cluster or None+ """+ match_cluster = None++ max_sim = -1+ max_param_count = -1+ max_cluster = None++ for cluster_id in cluster_ids:+ # Try to retrieve cluster from cache with bypassing eviction+ # algorithm as we are only testing candidates for a match.+ cluster = self.id_to_cluster.get(cluster_id)+ if cluster is None:+ continue+ cur_sim, param_count = self.get_seq_distance(cluster.log_template_tokens, tokens, include_params)+ if cur_sim > max_sim or (cur_sim == max_sim and param_count > max_param_count):+ max_sim = cur_sim+ max_param_count = param_count+ max_cluster = cluster++ if max_sim >= sim_th:+ match_cluster = max_cluster++ return match_cluster++ def create_template(self, seq1, seq2):+ assert len(seq1) == len(seq2)+ ret_val = list(seq2)++ for i, (token1, token2) in enumerate(zip(seq1, seq2)):+ if token1 != token2:+ ret_val[i] = self.param_str++ return ret_val++ def print_tree(self, file=None, max_clusters=5):+ self.print_node("root", self.root_node, 0, file, max_clusters)++ def print_node(self, token, node, depth, file, max_clusters):+ out_str = "\t" * depth++ if depth == 0:+ out_str += f"<{token}>"+ elif depth == 1:+ out_str += f"<L={token}>"+ else:+ out_str += f'"{token}"'++ if len(node.cluster_ids) > 0:+ out_str += f" (cluster_count={len(node.cluster_ids)})"++ print(out_str, file=file)++ for token, child in node.key_to_child_node.items():+ self.print_node(token, child, depth + 1, file, max_clusters)++ for cid in node.cluster_ids[:max_clusters]:+ cluster = self.id_to_cluster[cid]+ out_str = "\t" * (depth + 1) + str(cluster)+ print(out_str, file=file)++ def get_content_as_tokens(self, content):+ content = content.strip()+ for delimiter in self.extra_delimiters:+ content = content.replace(delimiter, " ")+ content_tokens = content.split()+ return content_tokens++ def add_log_message(self, content: str):+ content_tokens = self.get_content_as_tokens(content)++ if self.profiler:+ self.profiler.start_section("tree_search")+ match_cluster = self.tree_search(self.root_node, content_tokens, self.sim_th, False)+ if self.profiler:+ self.profiler.end_section()++ # Match no existing log cluster+ if match_cluster is None:+ if self.profiler:+ self.profiler.start_section("create_cluster")+ self.clusters_counter += 1+ cluster_id = self.clusters_counter+ match_cluster = LogCluster(content_tokens, cluster_id)+ self.id_to_cluster[cluster_id] = match_cluster+ self.add_seq_to_prefix_tree(self.root_node, match_cluster)+ update_type = "cluster_created"++ # Add the new log message to the existing cluster+ else:+ if self.profiler:+ self.profiler.start_section("cluster_exist")+ new_template_tokens = self.create_template(content_tokens, match_cluster.log_template_tokens)+ if tuple(new_template_tokens) == match_cluster.log_template_tokens:+ update_type = "none"+ else:+ match_cluster.log_template_tokens = tuple(new_template_tokens)+ update_type = "cluster_template_changed"+ match_cluster.size += 1+ # Touch cluster to update its state in the cache.+ # noinspection PyStatementEffect+ self.id_to_cluster[match_cluster.cluster_id]++ if self.profiler:+ self.profiler.end_section()++ return match_cluster, update_type++ def get_clusters_ids_for_seq_len(self, seq_len: int):+ """+ Return all clusters with the specified count of tokens+ """++ def append_clusters_recursive(node: Node, id_list_to_fill: list):+ id_list_to_fill.extend(node.cluster_ids)+ for child_node in node.key_to_child_node.values():+ append_clusters_recursive(child_node, id_list_to_fill)++ cur_node = self.root_node.key_to_child_node.get(str(seq_len))++ # no template with same token count+ if cur_node is None:+ return []++ target = []+ append_clusters_recursive(cur_node, target)+ return target++ def match(self, content: str, full_search_strategy="never"):+ """+ Match log message against an already existing cluster.+ Match shall be perfect (sim_th=1.0).+ New cluster will not be created as a result of this call, nor any cluster modifications.++ :param content: log message to match+ :param full_search_strategy: when to perform full cluster search.+ (1) "never" is the fastest, will always perform a tree search [O(log(n)] but might produce+ false negatives (wrong mismatches) on some edge cases;+ (2) "fallback" will perform a linear search [O(n)] among all clusters with the same token count, but only in+ case tree search found no match.+ It should not have false negatives, however tree-search may find a non-optimal match with+ more wildcard parameters than necessary;+ (3) "always" is the slowest. It will select the best match among all known clusters, by always evaluating+ all clusters with the same token count, and selecting the cluster with perfect all token match and least+ count of wildcard matches.+ :return: Matched cluster or None if no match found.+ """++ assert full_search_strategy in ["always", "never", "fallback"]++ required_sim_th = 1.0+ content_tokens = self.get_content_as_tokens(content)++ # consider for future improvement:+ # It is possible to implement a recursive tree_search (first try exact token match and fallback to+ # wildcard match). This will be both accurate and more efficient than the linear full search+ # also fast match can be optimized when exact match is required by early+ # quitting on less than exact cluster matches.+ def full_search():+ all_ids = self.get_clusters_ids_for_seq_len(len(content_tokens))+ cluster = self.fast_match(all_ids, content_tokens, required_sim_th, include_params=True)+ return cluster++ if full_search_strategy == "always":+ return full_search()++ match_cluster = self.tree_search(self.root_node, content_tokens, required_sim_th, include_params=True)+ if match_cluster is not None:+ return match_cluster++ if full_search_strategy == "never":+ return None++ return full_search()++ def get_total_cluster_size(self):+ size = 0+ for c in self.id_to_cluster.values():+ size += c.size+ return sizediff --git a/products/logs/backend/vendor/drain3/masking.py b/products/logs/backend/vendor/drain3/masking.pynew file mode 100644index 000000000000..c7c54b8ce132--- /dev/null+++ b/products/logs/backend/vendor/drain3/masking.py@@ -0,0 +1,107 @@+# Vendored from drain3 0.9.11 — https://github.com/IBM/Drain3+# Local changes: ruff-formatted/fixed.+#+# MIT License+#+# Copyright (c) 2020-2022 International Business Machines+# and the Drain3 project contributors.+#+# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:+#+# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.+#+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE.+# ruff: noqa+# mypy: ignore-errors+# SPDX-License-Identifier: MIT++import re+import abc+from collections.abc import Collection+from typing import Optional+++class AbstractMaskingInstruction(abc.ABC):+ def __init__(self, mask_with: str):+ self.mask_with = mask_with++ @abc.abstractmethod+ def mask(self, content: str, mask_prefix: str, mask_suffix: str) -> str:+ """+ Mask content according to this instruction and return the result.++ :param content: text to apply masking to+ :param mask_prefix: the prefix of any masks inserted+ :param mask_suffix: the suffix of any masks inserted+ """+ pass+++class MaskingInstruction(AbstractMaskingInstruction):+ def __init__(self, pattern: str, mask_with: str):+ super().__init__(mask_with)+ self.regex = re.compile(pattern)++ @property+ def pattern(self):+ return self.regex.pattern++ def mask(self, content: str, mask_prefix: str, mask_suffix: str) -> str:+ mask = mask_prefix + self.mask_with + mask_suffix+ return self.regex.sub(mask, content)+++# Alias for `MaskingInstruction`.+RegexMaskingInstruction = MaskingInstruction+++class LogMasker:+ def __init__(+ self, masking_instructions: Collection[AbstractMaskingInstruction], mask_prefix: str, mask_suffix: str+ ):+ self.mask_prefix = mask_prefix+ self.mask_suffix = mask_suffix+ self.masking_instructions = masking_instructions+ self.mask_name_to_instructions = {}+ for mi in self.masking_instructions:+ self.mask_name_to_instructions.setdefault(mi.mask_with, [])+ self.mask_name_to_instructions[mi.mask_with].append(mi)++ def mask(self, content: str) -> str:+ for mi in self.masking_instructions:+ content = mi.mask(content, self.mask_prefix, self.mask_suffix)+ return content++ @property+ def mask_names(self) -> Collection[str]:+ return self.mask_name_to_instructions.keys()++ def instructions_by_mask_name(self, mask_name: str) -> Optional[Collection[AbstractMaskingInstruction]]:+ return self.mask_name_to_instructions.get(mask_name, [])+++# Some masking examples+# ---------------------+#+# masking_instances = [+# MaskingInstruction(r'((?<=[^A-Za-z0-9])|^)(([0-9a-f]{2,}:){3,}([0-9a-f]{2,}))((?=[^A-Za-z0-9])|$)', "ID"),+# MaskingInstruction(r'((?<=[^A-Za-z0-9])|^)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})((?=[^A-Za-z0-9])|$)', "IP"),+# MaskingInstruction(r'((?<=[^A-Za-z0-9])|^)([0-9a-f]{6,} ?){3,}((?=[^A-Za-z0-9])|$)', "SEQ"),+# MaskingInstruction(r'((?<=[^A-Za-z0-9])|^)([0-9A-F]{4} ?){4,}((?=[^A-Za-z0-9])|$)', "SEQ"),+#+# MaskingInstruction(r'((?<=[^A-Za-z0-9])|^)(0x[a-f0-9A-F]+)((?=[^A-Za-z0-9])|$)', "HEX"),+# MaskingInstruction(r'((?<=[^A-Za-z0-9])|^)([\-\+]?\d+)((?=[^A-Za-z0-9])|$)', "NUM"),+# MaskingInstruction(r'(?<=executed cmd )(".+?")', "CMD"),+# ]diff --git a/products/logs/backend/vendor/drain3/simple_profiler.py b/products/logs/backend/vendor/drain3/simple_profiler.pynew file mode 100644index 000000000000..6e215728e1d6--- /dev/null+++ b/products/logs/backend/vendor/drain3/simple_profiler.py@@ -0,0 +1,165 @@+# Vendored via drain3 0.9.11 — originally SimpleProfiler by David Ohana.+# Local changes: ruff-formatted/fixed; ty annotation fixes. Apache-2.0; full license text at+# https://www.apache.org/licenses/LICENSE-2.0 (SPDX identifier + upstream source retained below).+# ruff: noqa+# mypy: ignore-errors+# SPDX-License-Identifier: Apache-2.0+# Based on https://github.com/davidohana/SimpleProfiler/blob/main/python/simple_profiler.py++import os+import time+from abc import ABC, abstractmethod+++class Profiler(ABC):+ @abstractmethod+ def start_section(self, section_name: str):+ pass++ @abstractmethod+ def end_section(self, section_name=""):+ pass++ @abstractmethod+ def report(self, period_sec=30):+ pass+++class NullProfiler(Profiler):+ """A no-op profiler. Use it instead of SimpleProfiler in case you want to disable profiling."""++ def start_section(self, section_name: str):+ pass++ def end_section(self, section_name=""):+ pass++ def report(self, period_sec=30):+ pass+++class SimpleProfiler(Profiler):+ def __init__(self, reset_after_sample_count=0, enclosing_section_name="total", printer=print, report_sec=30):+ self.printer = printer+ self.enclosing_section_name = enclosing_section_name+ self.reset_after_sample_count = reset_after_sample_count+ self.report_sec = report_sec++ self.section_to_stats = {}+ self.last_report_timestamp_sec = time.time()+ self.last_started_section_name = ""++ def start_section(self, section_name: str):+ """Start measuring a section"""++ if not section_name:+ raise ValueError("Section name is empty")+ self.last_started_section_name = section_name++ section = self.section_to_stats.get(section_name, None)+ if section is None:+ section = ProfiledSectionStats(section_name)+ self.section_to_stats[section_name] = section++ if section.start_time_sec != 0:+ raise ValueError(f"Section {section_name} is already started")++ section.start_time_sec = time.time()++ def end_section(self, name=""):+ """End measuring a section. Leave section name empty to end the last started section."""++ now = time.time()++ section_name = name+ if not name:+ section_name = self.last_started_section_name++ if not section_name:+ raise ValueError("Neither section name is specified nor a section is started")++ section: ProfiledSectionStats | None = self.section_to_stats.get(section_name, None)+ if section is None:+ raise ValueError(f"Section {section_name} does not exist")++ if section.start_time_sec == 0:+ raise ValueError(f"Section {section_name} was not started")++ took_sec = now - section.start_time_sec+ if 0 < self.reset_after_sample_count == section.sample_count:+ section.sample_count_batch = 0+ section.total_time_sec_batch = 0++ section.sample_count += 1+ section.total_time_sec += took_sec+ section.sample_count_batch += 1+ section.total_time_sec_batch += took_sec+ section.start_time_sec = 0++ def report(self, period_sec=30):+ """Print results using [printer] function. By default prints to stdout."""+ if time.time() - self.last_report_timestamp_sec < period_sec:+ return False++ enclosing_time_sec = 0+ if self.enclosing_section_name:+ enclosing_section: ProfiledSectionStats | None = self.section_to_stats.get(+ self.enclosing_section_name, None+ )+ if enclosing_section:+ enclosing_time_sec = enclosing_section.total_time_sec++ include_batch_rates = self.reset_after_sample_count > 0++ sections = self.section_to_stats.values()+ sorted_sections = sorted(sections, key=lambda it: it.total_time_sec, reverse=True)+ lines = map(lambda it: it.to_string(enclosing_time_sec, include_batch_rates), sorted_sections)+ text = os.linesep.join(lines)+ self.printer(text)++ self.last_report_timestamp_sec = time.time()+ return True+++class ProfiledSectionStats:+ def __init__(+ self,+ section_name,+ start_time_sec=0,+ sample_count=0,+ total_time_sec=0,+ sample_count_batch=0,+ total_time_sec_batch=0,+ ):+ self.section_name = section_name+ self.start_time_sec = start_time_sec+ self.sample_count = sample_count+ self.total_time_sec = total_time_sec+ self.sample_count_batch = sample_count_batch+ self.total_time_sec_batch = total_time_sec_batch++ def to_string(self, enclosing_time_sec: int, include_batch_rates: bool):+ took_sec_text = f"{self.total_time_sec:>8.2f} s"+ if enclosing_time_sec > 0:+ took_sec_text += f" ({100 * self.total_time_sec / enclosing_time_sec:>6.2f}%)"++ ms_per_k_samples = f"{1000000 * self.total_time_sec / self.sample_count: 7.2f}"++ if self.total_time_sec > 0:+ samples_per_sec = f"{self.sample_count / self.total_time_sec: 15,.2f}"+ else:+ samples_per_sec = "N/A"++ if include_batch_rates:+ ms_per_k_samples += f" ({1000000 * self.total_time_sec_batch / self.sample_count_batch: 7.2f})"+ if self.total_time_sec_batch > 0:+ samples_per_sec += f" ({self.sample_count_batch / self.total_time_sec_batch: 15,.2f})"+ else:+ samples_per_sec += " (N/A)"++ return (+ f"{self.section_name: <15}: took {took_sec_text}, "+ f"{self.sample_count: >10,} samples, "+ f"{ms_per_k_samples} ms / 1000 samples, "+ f"{samples_per_sec} hz"+ )