All files / src/core TokenNormalizer.ts

95.87% Statements 93/97
88.57% Branches 31/35
100% Functions 21/21
98.9% Lines 90/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505                                                                                                                                                                                                                                    139x                 5x 5x             1x     1x             3x 3x                     4x 4x   4x 4x 4x 4x   4x         4x             6378x             3x                                                             6x             6x                           6x 6x   6x 13x 13x 16x       16x 16x 16x 6x         13x     6x                                               6x           6x                           5x 5x   5x 6x 6x 6x 4x             5x   11x   5x                                                                                         17x             17x 17x                   17x           17x     13x     11x 11x 30x 30x     11x 11x 11x 12x 11x 11x         11x 30x   11x   11x 11x   11x 17x 17x     17x 49x     17x     17x 25x               17x 8x 8x         17x               14x       6x       8x 8x   8x 9x   9x 9x   9x       9x 9x         8x                       1x                     1x        
/**
 * Token Normalizer — Pre-clustering token sequence transformation pipeline.
 *
 * ## Purpose
 *
 * Addresses tokenization mismatches between parser output and ground truth
 * expectations. Some datasets (e.g., Proxifier) have Ground Truth templates
 * generated by non-standard tokenizers that produce different token granularity
 * than standard whitespace splitting. This module provides a pluggable pipeline
 * to normalize token sequences BEFORE Drain clustering.
 *
 * ## Architecture
 *
 * The TokenNormalizer is a Strategy pattern applied to token sequences:
 * - **Interface**: `TokenNormalizer` — a single `normalize` method
 * - **Pipeline**: `TokenNormalizerPipeline` — chains multiple normalizers
 * - **Built-in**: `AdjacentConstantFusion` — auto-detects and fuses constant pairs
 *
 * ## Why Pre-Clustering?
 *
 * The research-backed insight (validated against Loghub-2.0 benchmark and
 * logpai/logparser analysis) is that tokenization mismatches are a
 * **pre-clustering** problem, not a template creation problem:
 *
 * - LogSig (0.967 Proxifier GA): Uses term PAIRS — position-independent,
 *   length-independent matching. Completely sidesteps token count issue.
 * - LogCluster (0.951 Proxifier GA): Uses frequency-based clustering.
 * - Drain (0.527 Proxifier GA): Position-dependent, fixed-length. Cannot
 *   group messages with different token counts.
 *
 * Drain's fixed-depth prefix tree requires same-length messages to be routed
 * to the same branch. When the GT expects messages of different token counts
 * to be in the same group, token-level normalization is the only viable
 * approach without changing the core algorithm.
 *
 * ## Generic, Not Proxifier-Specific
 *
 * `AdjacentConstantFusion` makes ZERO assumptions about specific token values.
 * It only checks two universal properties:
 * 1. Both tokens are constant across ALL same-length messages
 * 2. Both tokens are "content words" (purely alphabetic, no punctuation, no params)
 *
 * These properties apply to ANY dataset where compound terms are consistently
 * adjacent in the token stream. The normalizer auto-detects which pairs to fuse.
 *
 * @module TokenNormalizer
 */
 
// ============================================================
// Core Types
// ============================================================
 
/**
 * Result of a token normalization operation.
 */
export interface NormalizationResult {
  /** The normalized token sequence */
  readonly tokens: readonly string[];
  /** Human-readable description of what was changed (for debugging) */
  readonly changes: string[];
}
 
/**
 * Pre-clustering token normalizer.
 *
 * Implementations can:
 * - Fuse adjacent tokens into compound tokens
 * - Split compound tokens into sub-tokens
 * - Add, remove, or reorder tokens
 * - Apply dataset-specific normalization rules
 */
export interface TokenNormalizer {
  /** Unique name for identification and debugging */
  readonly name: string;
 
  /**
   * Optional learning phase.
   *
   * Called once before processing a batch of messages. The normalizer
   * can analyze the batch to learn patterns (e.g., which adjacent tokens
   * should be fused).
   *
   * @param messages - Tokenized messages in the batch
   */
  learn?(messages: readonly (readonly string[])[]): void;
 
  /**
   * Normalize a single token sequence.
   *
   * Called for each message before Drain clustering. The normalized
   * sequence replaces the original for all subsequent processing.
   *
   * @param tokens - The tokenized message
   * @param paramStr - The parameter placeholder (e.g., "<*>")
   * @returns Normalization result with transformed tokens
   */
  normalize(
    tokens: readonly string[],
    paramStr: string,
  ): NormalizationResult;
}
 
// ============================================================
// Token Normalizer Pipeline
// ============================================================
 
/**
 * Pipeline of token normalizers, applied in registration order.
 *
 * Normalizers are applied sequentially: the output of one normalizer
 * becomes the input of the next. The `learn` phase is propagated to
 * all registered normalizers.
 */
export class TokenNormalizerPipeline {
  private normalizers: TokenNormalizer[] = [];
 
  /**
   * Registers a normalizer in the pipeline.
   *
   * @param normalizer - The normalizer to add
   * @returns this (fluent API)
   */
  register(normalizer: TokenNormalizer): this {
    this.normalizers.push(normalizer);
    return this;
  }
 
  /**
   * Registers multiple normalizers at once.
   */
  registerAll(normalizers: readonly TokenNormalizer[]): this {
    for (const n of normalizers) {
      this.register(n);
    }
    return this;
  }
 
  /**
   * Learning phase — propagates to all registered normalizers.
   */
  learn(messages: readonly (readonly string[])[]): void {
    for (const n of this.normalizers) {
      n.learn?.(messages);
    }
  }
 
  /**
   * Applies all normalizers in sequence to a token sequence.
   */
  normalize(
    tokens: readonly string[],
    paramStr: string,
  ): NormalizationResult {
    let current = tokens;
    const allChanges: string[] = [];
 
    for (const normalizer of this.normalizers) {
      const result = normalizer.normalize(current, paramStr);
      current = result.tokens;
      allChanges.push(
        ...result.changes.map(
          (c) => `[${normalizer.name}] ${c}`,
        ),
      );
    }
 
    return { tokens: current, changes: allChanges };
  }
 
  /**
   * Whether the pipeline has any registered normalizers.
   */
  get isEmpty(): boolean {
    return this.normalizers.length === 0;
  }
 
  /**
   * Number of registered normalizers.
   */
  get size(): number {
    return this.normalizers.length;
  }
}
 
// ============================================================
// Built-in: Regex Substitution (AEL-style aggressive preprocessing)
// ============================================================
 
/**
 * Replaces matched patterns with a substitution string in each token.
 *
 * Inspired by AEL's aggressive regex preprocessing: instead of wrapping
 * variable parts in masks, this fully REPLACES them with the paramStr.
 * This normalizes token counts by making all parameters the same length.
 *
 * ## Example: AEL-style number/IP replacement
 *
 * Input: ["192.168.1.1", "user", "123", "logged"]
 * Pattern: "\\d+" → replacement: "<*>"
 * Output: ["<*>", "user", "<*>", "logged"]
 *
 * ## Difference from Masking
 *
 * Masking wraps: "192.168.1.1" → "<IP>" (token count unchanged)
 * Substitution: "192.168.1.1" → "<*>" (token count still 1, but paramStr)
 *
 * The key advantage is that substitution normalizes the PARAMETER
 * representation, making param_count tracking consistent for
 * multi-dimension binning.
 */
export class RegexSubstitutionNormalizer implements TokenNormalizer {
  readonly name = "regex-substitution";
 
  /**
   * @param patterns - Regex patterns and replacement strings
   * @param replacement - Where to insert the substitution (default: "token")
   */
  constructor(
    private readonly patterns: ReadonlyArray<{
      /** Regex pattern to match in each token */
      readonly regex: RegExp;
      /** Replacement for matched content (use paramStr placeholder for param) */
      readonly replacement: string;
    }>,
  ) {}
 
  // Stateless — no learn phase needed
 
  normalize(
    tokens: readonly string[],
    paramStr: string,
  ): NormalizationResult {
    const result: string[] = [];
    const changes: string[] = [];
 
    for (const token of tokens) {
      let transformed = token;
      for (const { regex, replacement } of this.patterns) {
        const finalReplacement = replacement.replace(
          /\$\{paramStr\}/g,
          paramStr,
        );
        const before = transformed;
        transformed = transformed.replace(regex, finalReplacement);
        if (before !== transformed) {
          changes.push(
            `substituted "${before}" → "${transformed}" (pattern: ${regex.source})`,
          );
        }
      }
      result.push(transformed);
    }
 
    return { tokens: result, changes };
  }
}
 
/**
 * Collapses adjacent token groups matching regex patterns.
 *
 * Joins tokens into a temporary string, applies regex transformations,
 * and splits back into tokens. Useful for normalizing known optional
 * structures before applying AdjacentConstantFusion.
 *
 * ## Example: Proxifier KB parentheticals
 *
 * Input: ["bytes", "(18.4", "KB)", "sent"]
 * Pattern: match "(\\d+\\.\\d+\\s+KB\\)" → replace with ""
 * Output: ["bytes", "sent"]  (ready for AdjacentConstantFusion)
 *
 * ## Generic Design
 *
 * Patterns are specified as {regex, replacement} pairs. The regex is
 * applied to the joined token string (space-separated). Each matched
 * portion is replaced, then the result is split back into tokens.
 */
export class RegexCollapseNormalizer implements TokenNormalizer {
  readonly name = "regex-collapse";
 
  /**
   * @param patterns - Regex patterns and their replacements
   */
  constructor(
    private readonly patterns: ReadonlyArray<{
      /** Regex pattern to match in the joined token string */
      readonly regex: RegExp;
      /** Replacement string (use "" to remove) */
      readonly replacement: string;
    }>,
  ) {}
 
  // No learn phase needed — patterns are statically configured
 
  normalize(
    tokens: readonly string[],
    _paramStr: string,
  ): NormalizationResult {
    const changes: string[] = [];
    let joined = tokens.join(" ");
 
    for (const { regex, replacement } of this.patterns) {
      const before = joined;
      joined = joined.replace(regex, replacement);
      if (before !== joined) {
        changes.push(
          `collapsed pattern ${regex.source} → "${replacement}"`,
        );
      }
    }
 
    // Re-split, filtering empty tokens
    const result = joined
      .split(/\s+/)
      .filter((t) => t.length > 0);
 
    return { tokens: result, changes };
  }
}
 
// ============================================================
// Built-in: Adjacent Constant Fusion
// ============================================================
 
/**
 * Fuses adjacent constant tokens into compound tokens.
 *
 * ## Algorithm (Learn Phase)
 *
 * For the most common token length L in the batch:
 * 1. Filter to only messages of length L
 * 2. For each adjacent pair (i, i+1), check if BOTH tokens are:
 *    - Constant across ALL messages of length L
 *    - Content words (purely alphabetic, at least `minTokenLength` chars)
 *    - Not parameter placeholders (no `<` or `>`)
 * 3. Mark qualifying pairs for fusion
 *
 * ## Algorithm (Normalize Phase)
 *
 * 1. Only fuse if the message has the same token count as the learned pairs
 * 2. For each fusion pair, combine tokens with paramStr inserted between them
 * 3. Return the fused sequence
 *
 * ## Safety Guarantees
 *
 * - Only fuses tokens that are **demonstrably constant** across ALL messages
 * - Only applies to messages of the **same length** as the learned pairs
 * - Only fuses **content words** (no punctuation, no parameters)
 * - Each fusion **reduces** token count, improving cluster coherence
 *
 * ## Example: Proxifier
 *
 * Input (10 tokens):
 *   ["HOST", "close", "NUM", "bytes", "sent", "NUM", "bytes", "received", "lifetime", "DURATION"]
 *
 * Learned fusions: pos3+4 ("bytes"+"sent"), pos6+7 ("bytes"+"received")
 *
 * Output (8 tokens):
 *   ["HOST", "close", "NUM", "bytes<*>sent", "NUM", "bytes<*>received", "lifetime", "DURATION"]
 */
export class AdjacentConstantFusion implements TokenNormalizer {
  readonly name = "adjacent-constant-fusion";
 
  /**
   * @param minTokenLength - Minimum token length for content word detection (default: 2)
   * @param insertParamStr - Whether to insert paramStr between fused tokens (default: true)
   */
  constructor(
    private readonly minTokenLength: number = 2,
    private readonly insertParamStr: boolean = true,
  ) {}
 
  /**
   * Learned fusion pairs: Map of source position → destination position
   *
   * Each entry means: tokens[pos] and tokens[pos+1] should be fused.
   * Pairs are stored in descending order so fusing from back to front
   * doesn't affect earlier indices.
   */
  private fusionPositions: number[] = [];
 
  /**
   * The token length these fusion pairs apply to.
   * Messages of other lengths are not fused.
   */
  private applicableLength: number = 0;
 
  learn(messages: readonly (readonly string[])[]): void {
    if (messages.length < 2) return;
 
    // Find the most common token length
    const lengthCounts = new Map<number, number>();
    for (const msg of messages) {
      const len = msg.length;
      lengthCounts.set(len, (lengthCounts.get(len) ?? 0) + 1);
    }
 
    let maxCount = 0;
    let dominantLength = 0;
    for (const [len, count] of lengthCounts) {
      if (count > maxCount) {
        maxCount = count;
        dominantLength = len;
      }
    }
 
    // Need at least 2 messages of the same length to find constant pairs
    const sameLenMessages = messages.filter(
      (m) => m.length === dominantLength,
    );
    Iif (sameLenMessages.length < 2) return;
 
    this.applicableLength = dominantLength;
    this.fusionPositions = [];
 
    for (let i = 0; i < dominantLength - 1; i++) {
      const tokenI = sameLenMessages[0]![i]!;
      const tokenI1 = sameLenMessages[0]![i + 1]!;
 
      // Both tokens must be constant across all same-length messages
      const bothConstant = sameLenMessages.every(
        (m) => m[i] === tokenI && m[i + 1] === tokenI1,
      );
 
      Iif (!bothConstant) continue;
 
      // Both tokens must be content words (purely alphabetic)
      const isContentWord = (s: string): boolean => {
        return (
          s.length >= this.minTokenLength &&
          /^[a-zA-Z]+$/.test(s) &&
          !s.includes("<") &&
          !s.includes(">")
        );
      };
 
      if (isContentWord(tokenI) && isContentWord(tokenI1)) {
        this.fusionPositions.push(i);
        i++; // Skip next position to prevent overlapping fusion pairs
      }
    }
 
    // Sort descending so we can fuse from back to front without index shifts
    this.fusionPositions.sort((a, b) => b - a);
  }
 
  normalize(
    tokens: readonly string[],
    paramStr: string,
  ): NormalizationResult {
    // No learned fusions, or wrong length — pass through
    if (
      this.fusionPositions.length === 0 ||
      tokens.length !== this.applicableLength
    ) {
      return { tokens, changes: [] };
    }
 
    // Build fused token sequence
    const result = [...tokens];
    const changes: string[] = [];
 
    for (const pos of this.fusionPositions) {
      Iif (pos >= result.length - 1) continue;
 
      const left = result[pos]!;
      const right = result[pos + 1]!;
 
      const fused = this.insertParamStr
        ? `${left}${paramStr}${right}`
        : `${left}${right}`;
 
      result.splice(pos, 2, fused);
      changes.push(
        `fused tokens[${pos}]="${left}" + tokens[${pos + 1}]="${right}" → "${fused}"`,
      );
    }
 
    return { tokens: result, changes };
  }
}
 
// ============================================================
// Factory
// ============================================================
 
/**
 * Creates a default token normalizer pipeline (empty — no normalization).
 */
export function createDefaultNormalizerPipeline(): TokenNormalizerPipeline {
  return new TokenNormalizerPipeline();
}
 
/**
 * Creates a pipeline with AdjacentConstantFusion enabled.
 *
 * @param minTokenLength - Minimum alpha token length (default: 2)
 */
export function createExtendedNormalizerPipeline(
  minTokenLength: number = 2,
): TokenNormalizerPipeline {
  return new TokenNormalizerPipeline().register(
    new AdjacentConstantFusion(minTokenLength),
  );
}