Cordon: Semantic Anomaly Detection for System Logs

repository·main·Indexed 41 days ago

https://github.com/calebevans/cordon

Cordon is a semantic anomaly detection tool for large log files that utilizes transformer embeddings and k-NN density scoring to identify rare or unusual events. Version 1.1.1 includes a benchmark suite for evaluating template recall and rare pattern detection, supporting GPU acceleration via CUDA and MPS for embedding generation and scoring, as well as UMAP visualizations for high-dimensional embedding space analysis.

Tokens
24K
Snippets
58
Records
94
Agent score
51%

What's inside Cordon

  1. Understand Cordon benchmark performance on HDFS v1

    main

    The Cordon benchmark on the HDFS v1 dataset (from Loghub) evaluates the system's ability to detect anomalous log patterns, specifically focusing on template recall and rare pattern detection.

    Key Performance Drivers:

    • Sample Size: This is the most critical factor. Template recall improves significantly as sample size increases (e.g., from 58% at 50k lines to 97% at 5M lines). Stability (measured by Coefficient of Variation) also improves as sample size grows.
    • Model Size: Embedding model size (e.g., BGE-large vs. MiniLM) has no significant impact on performance for HDFS logs.
    • Parameter Tuning: Adjusting window size (w) and k-neighbors (k) provides only marginal improvements (~2%) and does not solve instability issues caused by small sample sizes.
    • Thresholds: Varying the anomaly percentile threshold (p) affects traditional precision/recall but has minimal impact on template-level metrics.

    Recommendation: Cordon is most effective and stable when used with large log files (≥500k lines) where comprehensive sampling is possible.

  2. Understand Cordon benchmark metrics

    main

    Cordon evaluates semantic uniqueness detection using several specialized metrics:

    • Template Recall: The fraction of unique anomaly types detected (measures diversity of detection).
    • Rare Template Recall: The fraction of rare templates (those with < 100 occurrences) detected.
    • Frequency-Weighted Recall: An inverse-frequency weighted metric where finding rare patterns results in a higher score.
    • Traditional Metrics (Precision/Recall/F1): Line-level metrics used for comparison. Note that these are expected to be low (0.05-0.15) for systems designed to ignore repetitive patterns.
  3. Configure Cordon backends

    main

    Cordon supports three primary backends for embedding generation:

    1. sentence-transformers (Default)

    Best for native installations with local GPU access.

    • Use --device cuda or --device cpu to specify the hardware.

    2. llama.cpp Backend

    Best for container deployments using GPU acceleration via Vulkan.

    • Use --backend llama-cpp.
    • Specify layers with --n-gpu-layers <int>.
    • Specify a custom model with --model-path <path>.

    3. Remote API Backend

    Uses LiteLLM to connect to providers like OpenAI, Gemini, or Cohere.

    • Use --backend remote.
    • Specify the model with --model-name <provider>/<model>.
    • Provide an API key via --api-key <key> or environment variables (e.g., OPENAI_API_KEY, GEMINI_API_KEY, COHERE_API_KEY).
    • Specify a custom endpoint with --endpoint <url> for OpenAI-compatible APIs.
    cordon --backend remote --model-name openai/text-embedding-3-small --api-key $OPENAI_API_KEY system.log
  4. How Cordon detects anomalies using semantic uniqueness

    main

    Cordon identifies anomalies based on semantic uniqueness rather than traditional pattern matching or frequency analysis.

    In log analysis, repetitive patterns (even errors) are considered normal. Cordon focuses on identifying patterns that are semantically unusual compared to the surrounding context. This approach allows it to distinguish between a common error that repeats frequently and a critical, unique error that appears only once, which is treated as more anomalous.

  5. Configure Ingestion and Windowing

    main

    Cordon converts variable-length logs into fixed-size semantic units using non-overlapping windows. This ensures each log line appears in exactly one window, providing clear boundaries and efficient processing.

    Default Configuration:

    • window_size: 4 (lines per window)
    • max_line_length: None (optional limit to split lines)

    Example Behavior: If you have log lines [1, 2, 3, 4, 5, 6, 7, 8], a window_size of 4 results in:

    • Window 1: [1, 2, 3, 4]
    • Window 2: [5, 6, 7, 8]
  6. Understand Cordon's template-level metrics

    main

    Cordon prioritizes the diversity of anomaly types over the total count of anomalous lines. Therefore, users should evaluate performance using Template-Level Metrics rather than traditional line-level metrics.

    Primary Metrics

    • Template Recall: The fraction of unique anomaly template types detected. High recall indicates comprehensive coverage of different anomaly patterns.
    • Rare Template Recall: The fraction of templates with < 100 occurrences that are detected. This measures the ability to find infrequent but critical patterns.
    • Frequency-Weighted Recall: An inverse-frequency weighted score where rare patterns are weighted higher. A higher score indicates the system is successfully biasing toward unique pattern detection.

    Reference Metrics

    • Line-Level F1, Precision, Recall: Standard metrics that count every instance. These are expected to be low (e.g., 0.05-0.08) because Cordon ignores repetitive patterns to focus on type diversity.
  7. Why Cordon is used for LLM log analysis

    main

    Cordon addresses several limitations of using Large Language Models (LLMs) for raw log analysis:

    • Context Limits: Even with large windows (e.g., Gemini 2.5 Pro's ~1M tokens), raw logs can exceed capacity.
    • Quality Degradation: LLM performance decreases as context fills with repetitive, low-signal content.
    • Cost Scaling: Processing massive amounts of repetitive logs increases token costs.
    • Signal-to-Noise Ratio: Repetitive content buries important information.

    Cordon's Benefit: It reduces log volume (benchmarked at 98% reduction on 1M-5M line HDFS logs with $p=0.02$ threshold) while retaining semantically interesting content, making it more efficient for LLM consumption.

  8. How Cordon's scoring and filtering works

    main

    Cordon calculates a score for each window of log lines based on its semantic uniqueness.

    • Higher score: Semantically unique/anomalous.
    • Lower score: Repetitive/normal background noise.

    The score is the average cosine distance to its $k$ nearest neighbors in the embedding space.

    Important Behavior: Repetitive patterns are filtered even if they are critical. For example, a FATAL error repeated 100 times will score as "normal" because it is semantically similar to itself. This allows the tool to surface unusual events rather than just important ones.

  9. Interpret Cordon benchmark visualizations

    main

    When running with --generate-plots, two main visualizations are produced:

    1. UMAP Projection (umap_*.png)

    Shows a 2D projection of the high-dimensional embedding space.

    • Left Panel (k-NN score): Uses a plasma scale (dark purple = low score $\rightarrow$ orange/yellow = high score). Isolated orange/yellow points indicate detected anomalies.
    • Right Panel (Ground Truth): Colored by dataset labels (Red = Anomaly sessions, Green = Normal sessions).
    • Interpretation: High scores (orange/yellow) on the left that align with red points on the right indicate correct detection. Dense dark purple regions indicate normal, repetitive patterns.

    2. Template Coverage Chart (template_coverage_*.png)

    A horizontal bar chart showing detection success rates for each unique anomaly template.

    • Y-axis: Template IDs (sorted by frequency).
    • X-axis: Occurrence count (log scale).
    • Green Bars: Successfully detected templates.
    • Red Bars: Missed templates.
    • Goal: Look for green bars in the shorter (rarer) bars to verify the system's ability to detect rare patterns.
  10. Understand the Template-Level Evaluation Methodology

    main

    Cordon uses a template-level evaluation methodology instead of traditional line-level metrics (Precision, Recall, F1). Traditional metrics reward systems for flagging repetitive, common errors. Cordon's methodology prioritizes semantic uniqueness, measuring the diversity of anomaly types (templates) detected rather than the quantity of individual log lines flagged.

    Key Metrics

    • Template Recall: The fraction of unique anomaly templates detected. Template Recall = |Detected Templates ∩ Anomaly Templates| / |Anomaly Templates|
    • Rare Template Recall: The fraction of rare templates (defined as templates with < 100 occurrences) detected.
    • Frequency-Weighted Recall: Uses inverse-frequency weighting to give higher value to finding rare templates. Weight(template) = 1 / occurrence_count FW Recall = Σ weights(detected) / Σ weights(all anomalies)

    Line-Level Template Attribution

    To ensure credit is only given for templates the system actually identifies, the evaluation follows these steps for each flagged log line:

    1. Parse the line.
    2. Match it to a template using regex patterns.
    3. Credit the template only if it appears in the flagged line itself (not just within the same session).
  11. Understand Cordon's limitations and methodology constraints

    main

    When interpreting Cordon's performance or applying it to new datasets, consider these technical limitations:

    Data & Model Constraints

    • Template Dependency: Evaluation requires pre-parsed templates. If your dataset lacks template ground truth, you must perform template extraction (e.g., using Drain) first.
    • Embedding Dependency: Results are highly dependent on the quality of the semantic embeddings used.
    • Anomaly Diversity: The current benchmark is based on HDFS v1, which has limited anomaly types. Performance may vary on datasets with hundreds of anomaly types.

    Algorithmic Constraints

    • No Temporal Metrics: Cordon does not measure detection latency, temporal ordering, or streaming performance.
    • No Severity Weighting: All anomalies are treated equally; the tool does not account for business impact or severity.
    • k-NN Density Assumptions: The approach assumes semantic isolation indicates an anomaly. This may fail for normal but rare operations (like startup sequences) or clustered anomalies.
    • Percentile Thresholding: Using anomaly_percentile is adaptive but might flag near-identical content as anomalous in extremely uniform logs.
  12. How the Cordon high-level algorithm works

    main

    Cordon uses density scoring in semantic embedding space to reduce log volume while preserving signal. The process follows these steps:

    1. Chunking: Logs are divided into non-overlapping windows (e.g., 10 lines per window).
    2. Embedding: Each window is converted into a 384-dimensional vector using a transformer model.
    3. k-NN Distance Calculation: For every embedding, the algorithm finds its $k$ nearest neighbors.
    4. Scoring: A score is calculated as the average distance to these $k$ nearest neighbors.
    5. Anomaly Identification: Higher scores indicate an embedding is farther from its neighbors, marking it as more anomalous.
    6. Filtering: The system keeps the top $X$% highest-scoring windows.
    7. Merging: Adjacent windows are merged into contiguous blocks to maintain context.
    1. Chunk logs into non-overlapping windows (e.g., 10 lines per window)
    2. Embed each window using a transformer model → 384-dimensional vectors
    3. For each embedding, compute k-NN distance to find "neighbors"
    4. Score = average distance to k nearest neighbors
    5. Higher score = farther from neighbors = more anomalous
    6. Keep top X% highest-scoring windows
    7. Merge adjacent windows into contiguous blocks