Compare commits

...
2 Commits
Author SHA1 Message Date
Claude 5323e6c71a Add classic-ml-vs-llm module: Tribuo 4.3.2 and Smile 7.3.0 text classifiers, a zero-shot LLM client and a cost model
Seeded synthetic support tickets in five categories; Tribuo and Smile logistic regression and Smile naive Bayes against a
majority baseline; skewed classes, train/test duplicates, vocabulary drift and the three different answers to a ticket of
unseen words; a zero-shot client for OpenAI-compatible endpoints tested against a fake endpoint (no model was called) and
a cost formula with assumed prices. Every figure is written to output/ by the tests that assert it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b69H5rTewUKPyhGS8r
2026-12-01 23:57:00 +05:30
asmhatreandClaude Sonnet 5.5 dc94d7fece Add log-anomaly module: Spring Boot log parser, template mining, swappable embedder, k-means baseline, novel-template and rate-spike detectors with measured blind spots, incidents and a template-only summary prompt on Spring Boot 4.2.0
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b69H5rTewUKPyhGS8r
2026-12-01 23:57:00 +05:30
81 changed files with 3493 additions and 0 deletions
+4
View File
@@ -20,6 +20,8 @@ facts, so the build fails when a claim stops being true.
| `mcp-stateless` | MCP 2026-07-28 for Java Developers: Migrating an MCP Server to the Stateless Spec | one order server as a 2025-era stateful and a 2026-07-28 stateless Spring AI server, behind a round-robin balancer, with multi-round-trip requests, a version router and real SDK clients |
| `code-search-mcp` | Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings) | JavaParser indexes a four-module sample monorepo, a swappable `Embedder` (offline hashing or any `/v1/embeddings` endpoint) ranks methods by what they do, `find_usages` compares name matching with the symbol solver, and the three tools are served on the 2026-07-28 stateless spec with the 2.2.0 modern SDK, tested over raw HTTP, two server instances and the SDK client |
| `release-notes-ai` | AI Release Notes and PR Descriptions in Java: JGit, Spring AI and Gitea | JGit reads a real repository, commits are grouped by Conventional Commit type, release notes and a version bump are computed in code, a Spring AI model writes only the opening paragraph behind a guard that rejects invented PR numbers and hashes, and a Gitea client creates or updates the release and PR so a rerun edits instead of failing; tested with a stub model and a local fake Gitea |
| `log-anomaly` | AI Log Anomaly Detection for Spring Boot: Embeddings and Clustering | a parser for Spring Boot's own log layout, template mining, an `Embedder` seam (offline hashing or any `/v1/embeddings` endpoint), k-means over normal templates, a novel-template detector and a rate-spike detector with their measured blind spots, incidents, and a summary prompt that is 0.4% of the raw window; tested on seeded synthetic logs and on a log file Spring Boot 4.2.0 wrote itself |
| `classic-ml-vs-llm` | Text Classification in Java Without an LLM: Tribuo vs Smile vs a Zero-Shot LLM | 3000 seeded synthetic support tickets in five categories; Tribuo and Smile logistic regression and Smile naive Bayes against a majority baseline, with accuracy, macro-F1, latency and model size; skewed classes, train/test duplicates, vocabulary drift and the three different answers to a ticket of unseen words; a zero-shot LLM client tested against a fake endpoint (no model was called) and a cost formula with assumed prices |
## Versions (verified on Maven Central, 2026-10-11)
@@ -46,6 +48,8 @@ facts, so the build fails when a claim stops being true.
| Claude Code CLI | 2.1.330 | `claude mcp` run for `claude-code-spring/output/08`; the model-side behaviour is documented, not executed |
| Spring Boot / Spring AI / MCP Java SDK (`mcp-stateless`) | 4.2.0 / 2.1.0 / 2.2.0 | verified on Maven Central 2026-11-22; this module overrides the Spring versions above |
| MCP Java SDK / JavaParser (`code-search-mcp`) | 2.2.0 / 3.28.2 | verified on Maven Central 2026-11-25; `code-search-mcp` only. The 2026-07-28 "modern" server API (`io.modelcontextprotocol.modern`) is in `mcp-core` 2.2.0; JavaParser 3.28.2 cannot resolve calls to implicit record accessors |
| Spring Boot (`log-anomaly`) | 4.2.0 | verified on Maven Central 2026-12-01; `log-anomaly` only. No Spring AI and no model download: the embedder and the summariser are seams, tested offline |
| Tribuo `tribuo-classification-sgd` / Smile `smile-core` | 4.3.2 / 7.3.0 | verified on Maven Central 2026-12-01; `classic-ml-vs-llm` only. Tribuo is Apache-2.0 and Java 8 bytecode; Smile 7.3.0 is GPL-3.0-or-later or a commercial licence, and its bytecode needs Java 25 |
| JDK | 25 LTS | |
| JUnit | 6.1.3 | |
+31
View File
@@ -0,0 +1,31 @@
# classic-ml-vs-llm
Companion module for the ankurm.com post *Text Classification in Java Without an LLM: Tribuo vs Smile vs a Zero-Shot LLM*.
Five support-ticket categories, a seeded generator for 3000 synthetic tickets, three classic classifiers
(Tribuo `LogisticRegression`, Smile `LogisticRegression`, Smile `DiscreteNaiveBayes`), a majority-class baseline, and a
zero-shot client for any OpenAI-compatible endpoint. Every figure in the post comes from `output/`, written by the tests.
```bash
export JAVA_HOME=/path/to/jdk-25 # Smile 7.3.0 is compiled for Java 25
scripts/run-all.sh # or: mvn test -pl classic-ml-vs-llm
```
**The data is synthetic.** Accuracy on it measures the harness, not your tickets. **No LLM was called** while this module was
written: `ZeroShotLlm` is tested against a local fake endpoint, so no LLM accuracy figure exists here. To measure one, call
`new ZeroShotLlm(baseUrl, model, apiKey).score(test)` on `Fixtures.SPLIT.test()` against your own endpoint.
| Output | Shows |
|---|---|
| `01-dataset.txt` | class counts, train/test duplicates, sample tickets |
| `02-models.txt` | accuracy, macro-F1, training time, latency, model size; Tribuo's evaluator against ours |
| `03-confusion-tribuo.txt` | confusion matrix and per-class precision/recall |
| `04-imbalance.txt` | accuracy against macro-F1 on skewed classes |
| `05-duplicates.txt` | accuracy on tickets seen in training against unseen ones |
| `06-vocabulary-drift.txt` | the drop when the wording changes |
| `07-no-known-words.txt` | three libraries, three behaviours on a ticket of unseen words |
| `08-llm-harness.txt` | request shape and reply guard, against a fake endpoint |
| `09-cost-model.txt` | cost formula with assumed prices |
| `10-class-file-versions.txt` | the Java version each library's bytecode needs |
Timing columns drift between runs and machines. Accuracy and F1 are deterministic.
+23
View File
@@ -0,0 +1,23 @@
# The synthetic ticket set and its split
generator: seed 42, 3000 tickets, 15% carry a second complaint from another class, 12% have a typo,
3% have a randomly wrong label (human labelling noise)
## Class counts
class train test
BILLING 474 118
ACCESS 474 118
BUG 484 121
FEATURE 485 121
CANCEL 484 121
total 2401 599
## Exact duplicates between train and test
test tickets whose normalised text also appears in train: 122 of 599
## Six tickets, first six of the test set
BUG | Search returns an empty list although the data exists. Also, I was charged twice for this month.
BUG | Hello, The app freezes on the dashboard. The order number ends 4471. Thank you
BILLING | Good morning, My invoice shows the wrong amount. I am on the Pro plan. Thanks.
BUG | Hello, The app freezes on the dashboard. I am using Chrome on Windows. Please advise.
BILLING | Good morning, There is a charge on my statement I do not recognise. My account email is on file. Thank you
ACCESS | Urgent: The reset password email nevre arrives. Regards, Priya
+15
View File
@@ -0,0 +1,15 @@
# Three classic classifiers and a baseline on the same split
dataset: 3000 synthetic tickets, 2401 train / 599 test, 5 balanced classes (see 01-dataset.txt)
timings are from one run on one machine and drift between runs; accuracy and F1 do not
model accuracy macro-F1 train ms median us p99 us model KB
Majority-class baseline 0.2020 0.0672 5 0.1 0.4 -
Tribuo LogisticRegression (SGD) 0.9232 0.9233 1141 13.9 93.2 58.9
Smile LogisticRegression 0.9182 0.9182 2796 7.3 45.2 10.1
Smile DiscreteNaiveBayes 0.9048 0.9049 49 7.5 31.9 16.9
## Tribuo's own evaluator against ours
Tribuo LabelEvaluator accuracy : 0.9232
harness Metrics accuracy : 0.9232
Tribuo LabelEvaluator macro F1 : 0.9233
harness Metrics macro F1 : 0.9233
@@ -0,0 +1,15 @@
# Tribuo logistic regression: where the mistakes go
rows are the true category, columns the predicted one
actual\pred BILLING ACCESS BUG FEATURE CANCEL
BILLING 108 1 3 2 4
ACCESS 1 111 3 2 1
BUG 1 1 116 1 2
FEATURE 2 4 5 107 3
CANCEL 1 4 5 0 111
BILLING precision 0.956 recall 0.915 F1 0.935
ACCESS precision 0.917 recall 0.941 F1 0.929
BUG precision 0.879 recall 0.959 F1 0.917
FEATURE precision 0.955 recall 0.884 F1 0.918
CANCEL precision 0.917 recall 0.917 F1 0.917
@@ -0,0 +1,6 @@
# Skewed classes: accuracy against macro-F1
class mix 55% BILLING, 25% ACCESS, 12% BUG, 6% FEATURE, 2% CANCEL; 2399 train / 601 test
model accuracy macro-F1 CANCEL recall
Majority-class baseline 0.5308 0.1387 0.000
Tribuo LogisticRegression (SGD) 0.9318 0.9083 0.800
@@ -0,0 +1,6 @@
# Tickets the model has already seen
Tribuo logistic regression, balanced split from 02-models.txt
test tickets also in train : 122 accuracy 0.9836
test tickets never seen : 477 accuracy 0.9078
whole test set : 599 accuracy 0.9232
@@ -0,0 +1,8 @@
# Tickets that use words the model never saw
trained on the balanced set; tested on 1000 new tickets where ACCESS and BUG use new wording
(passkey, magic link, device verification, editor glitches, widget flickers, sync spinner)
model normal drifted ACCESS rec. BUG rec.
Tribuo LogisticRegression (SGD) 0.9232 0.6990 0.580 0.172
Smile LogisticRegression 0.9182 0.6970 0.488 0.263
Smile DiscreteNaiveBayes 0.9048 0.7190 0.605 0.239
@@ -0,0 +1,8 @@
# A ticket made only of words the model has never seen
input: "Device verification loops forever." (none of these words occur in the training tickets)
Tribuo LogisticRegression raw : throws IllegalArgumentException: No features found in Example ArrayExample(...)
Smile LogisticRegression raw : returns class index 1 (ACCESS), a guess from the intercepts alone
Smile DiscreteNaiveBayes raw : returns -2147483648 (Integer.MIN_VALUE, not a class index)
harness wrappers (predict) : null / null / null (null = no answer, counted as wrong)
@@ -0,0 +1,22 @@
# Zero-shot client against a fake endpoint (wiring only, no model)
NO LLM WAS CALLED. A local server returns scripted replies, so this shows request shape and reply handling.
## Reply guard, ZeroShotLlm.parse
"BILLING" -> BILLING (accepted)
"Access." -> ACCESS (accepted)
"The category is Bug" -> BUG (accepted)
"BILLING or CANCEL" -> (none) (rejected: two categories)
"I think this is a refund request" -> (none) (rejected: no category name)
"" -> (none) (rejected: empty)
## Five scripted replies through the real HTTP client
scripted: BILLING, ACCESS, Probably BUG., FEATURE or BILLING, CANCEL
right 4 of 5, unparseable 1 (the ambiguous reply counts as wrong, never as a guess)
## The first request body, verbatim
{"model":"any-model","temperature":0,"max_tokens":8,"messages":[{"role":"system","content":"You classify customer support tickets. Reply with exactly one word from this list and nothing else: BILLING, ACCESS, BUG, FEATURE, CANCEL. BILLING is about charges, invoices and refunds. ACCESS is about login, passwords and locked accounts. BUG is about something that is broken. FEATURE is a request for something new. CANCEL is about ending a subscription or account."},{"role":"user","content":"Ticket: I was charged twice for this month.\nCategory:"}]}
Authorization header: Bearer test-key
## Prompt size across the real test tickets (estimate: characters / 4)
instruction alone : 93 tokens
average per ticket : 117.9 tokens (instruction + ticket)
@@ -0,0 +1,18 @@
# What a million tickets cost: a formula, not a price list
EVERY PRICE BELOW IS AN ASSUMPTION. Replace the three rate cards with the ones you actually pay.
inputs: 117.9 prompt tokens per ticket (estimate), 3 output tokens, 1,000,000 tickets
## LLM, billed per token (output priced at 5x input in every row)
assumed $ per 1M input tokens $ per 1M tickets
0.10 13.29
1.00 132.92
3.00 398.76
## Classic model, in-process on one CPU core
measured median predict (Tribuo, 02-models.txt run): 13.9 microseconds
assumed core price: $0.05 per core-hour
core-seconds for 1M tickets: 13.9 cost: $0.0002
Not in either number: training and labelling for the classic model, retries and rate limits for the LLM,
and the engineer-hours for both. They usually decide the real comparison.
@@ -0,0 +1,5 @@
# The Java version each library's bytecode needs
class-file major version 52 = Java 8, 61 = Java 17, 65 = Java 21, 69 = Java 25
Tribuo 4.3.2 org.tribuo.Model major 52 (Java 8)
Smile 7.3.0 smile.classification.Maxent major 69 (Java 25)
+50
View File
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm.agents</groupId>
<artifactId>java-ai-agents</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>classic-ml-vs-llm</artifactId>
<name>Text classification in Java without an LLM: Tribuo vs Smile vs a zero-shot LLM</name>
<properties>
<!-- Verified on Maven Central 2026-12-01 -->
<tribuo.version>4.3.2</tribuo.version>
<smile.version>7.3.0</smile.version>
</properties>
<dependencies>
<dependency>
<groupId>org.tribuo</groupId>
<artifactId>tribuo-classification-sgd</artifactId>
<version>${tribuo.version}</version>
</dependency>
<dependency>
<groupId>com.github.haifengl</groupId>
<artifactId>smile-core</artifactId>
<version>${smile.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Regenerates every file in classic-ml-vs-llm/output/ by running the tests that assert the same facts.
# Needs JDK 25 (Smile 7.3.0's bytecode is Java 25) and Maven. No network after the first dependency download, no API key.
set -euo pipefail
cd "$(dirname "$0")/../.."
rm -f classic-ml-vs-llm/output/*.txt
mvn -B -pl classic-ml-vs-llm test
ls -1 classic-ml-vs-llm/output
@@ -0,0 +1,4 @@
package com.ankurm.classicml;
/** The five ticket categories used throughout the module. */
public enum Category { BILLING, ACCESS, BUG, FEATURE, CANCEL }
@@ -0,0 +1,22 @@
package com.ankurm.classicml;
/**
* A plain cost model, not a measurement. Every price is a parameter you must replace with the rate card you
* actually pay; the tests print the formula's output for a few round numbers so the shape is visible.
*/
public final class CostModel {
private CostModel() { }
/** Dollars to classify {@code tickets} tickets through an LLM billed per million tokens. */
public static double llmDollars(long tickets, double promptTokens, double outputTokens,
double dollarsPerMillionInput, double dollarsPerMillionOutput) {
return tickets * (promptTokens * dollarsPerMillionInput + outputTokens * dollarsPerMillionOutput) / 1_000_000.0;
}
/** Dollars of CPU time to classify {@code tickets} tickets in-process on one core billed per hour. */
public static double cpuDollars(long tickets, double microsPerTicket, double dollarsPerCoreHour) {
double coreSeconds = tickets * microsPerTicket / 1_000_000.0;
return coreSeconds / 3600.0 * dollarsPerCoreHour;
}
}
@@ -0,0 +1,21 @@
package com.ankurm.classicml;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/** Always answers the commonest training label. If a model cannot beat this, it has learned nothing. */
public final class MajorityBaseline implements TextClassifier {
private Category majority = Category.BILLING;
@Override public String name() { return "Majority-class baseline"; }
@Override public void train(List<Ticket> train) {
Map<Category, Integer> n = new EnumMap<>(Category.class);
for (Ticket t : train) n.merge(t.label(), 1, Integer::sum);
majority = n.entrySet().stream().max(Map.Entry.comparingByValue()).orElseThrow().getKey();
}
@Override public Category predict(String text) { return majority; }
}
@@ -0,0 +1,81 @@
package com.ankurm.classicml;
import java.util.List;
import java.util.Locale;
/** Accuracy, per-class precision/recall/F1 and the confusion matrix, computed once for every contender. */
public final class Metrics {
private final int k = Category.values().length;
/** confusion[actual][predicted] */
private final int[][] confusion = new int[k][k];
private final int[] support = new int[k];
private int total;
private int unanswered;
public static Metrics of(TextClassifier model, List<Ticket> test) {
Metrics m = new Metrics();
for (Ticket t : test) m.add(t.label(), model.predict(t.text()));
return m;
}
public static Metrics ofPredictions(List<Category> actual, List<Category> predicted) {
Metrics m = new Metrics();
for (int i = 0; i < actual.size(); i++) m.add(actual.get(i), predicted.get(i));
return m;
}
void add(Category actual, Category predicted) {
support[actual.ordinal()]++;
if (predicted == null) unanswered++;
else confusion[actual.ordinal()][predicted.ordinal()]++;
total++;
}
/** Tickets the model declined to answer. They count against accuracy and recall. */
public int unanswered() { return unanswered; }
public int total() { return total; }
public int[][] confusion() { return confusion; }
public double accuracy() {
int right = 0;
for (int i = 0; i < k; i++) right += confusion[i][i];
return total == 0 ? 0 : (double) right / total;
}
public double precision(Category c) {
int i = c.ordinal(), predicted = 0;
for (int a = 0; a < k; a++) predicted += confusion[a][i];
return predicted == 0 ? 0 : (double) confusion[i][i] / predicted;
}
public double recall(Category c) {
int i = c.ordinal();
return support[i] == 0 ? 0 : (double) confusion[i][i] / support[i];
}
public double f1(Category c) {
double p = precision(c), r = recall(c);
return p + r == 0 ? 0 : 2 * p * r / (p + r);
}
/** Unweighted mean of per-class F1. A class with no support counts as 0, which is the strict reading. */
public double macroF1() {
double s = 0;
for (Category c : Category.values()) s += f1(c);
return s / k;
}
public String confusionTable() {
StringBuilder sb = new StringBuilder();
sb.append(String.format(Locale.ROOT, "%-10s", "actual\\pred"));
for (Category c : Category.values()) sb.append(String.format(Locale.ROOT, "%9s", c));
for (Category a : Category.values()) {
sb.append('\n').append(String.format(Locale.ROOT, "%-11s", a));
for (Category p : Category.values()) sb.append(String.format(Locale.ROOT, "%9d", confusion[a.ordinal()][p.ordinal()]));
}
return sb.toString();
}
}
@@ -0,0 +1,112 @@
package com.ankurm.classicml;
import smile.classification.DiscreteNaiveBayes;
import smile.classification.LogisticRegression;
import smile.feature.extraction.BagOfWords;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Smile 7.3.0. Two classifiers share one {@link BagOfWords} vocabulary built from the training tickets only:
* a multinomial logistic regression on dense counts, and a multinomial naive Bayes on the same counts.
*/
public final class SmileClassifiers {
private SmileClassifiers() { }
/** Words seen at least {@code minCount} times in training, in a stable order. */
static String[] vocabulary(List<Ticket> train, int minCount) {
Map<String, Integer> n = new HashMap<>();
for (Ticket t : train) for (String w : Tokens.of(t.text())) n.merge(w, 1, Integer::sum);
List<String> words = new ArrayList<>();
n.forEach((w, c) -> { if (c >= minCount) words.add(w); });
words.sort(null);
return words.toArray(String[]::new);
}
/** Multinomial logistic regression, the same model family as the Tribuo contender. */
public static final class Logistic implements TextClassifier {
private BagOfWords bow;
private String[] vocab;
private LogisticRegression model;
@Override public String name() { return "Smile LogisticRegression"; }
@Override public void train(List<Ticket> train) {
vocab = vocabulary(train, 2);
bow = new BagOfWords(Tokens::of, vocab);
double[][] x = new double[train.size()][];
int[] y = new int[train.size()];
for (int i = 0; i < x.length; i++) {
x[i] = toDouble(bow.apply(train.get(i).text()));
y[i] = train.get(i).label().ordinal();
}
model = LogisticRegression.fit(x, y);
}
/** Returns {@code null} when no word of the ticket is in the vocabulary: the library would answer from the bias alone. */
@Override public Category predict(String text) {
return allZero(bow.apply(text)) ? null : Category.values()[rawPredict(text)];
}
/** Calls Smile directly. With no known words this silently returns whichever class the intercepts favour. */
public int rawPredict(String text) {
return model.predict(toDouble(bow.apply(text)));
}
public LogisticRegression model() { return model; }
/** What you would have to ship: the fitted model and the vocabulary that maps words to columns. */
public Object[] shippable() { return new Object[] {model, vocab}; }
}
/** Multinomial naive Bayes: no optimiser at all, one pass over the counts. */
public static final class NaiveBayes implements TextClassifier {
private BagOfWords bow;
private String[] vocab;
private DiscreteNaiveBayes model;
@Override public String name() { return "Smile DiscreteNaiveBayes"; }
@Override public void train(List<Ticket> train) {
vocab = vocabulary(train, 2);
bow = new BagOfWords(Tokens::of, vocab);
model = new DiscreteNaiveBayes(DiscreteNaiveBayes.Model.MULTINOMIAL, Category.values().length, vocab.length);
int[][] x = new int[train.size()][];
int[] y = new int[train.size()];
for (int i = 0; i < x.length; i++) {
x[i] = bow.apply(train.get(i).text());
y[i] = train.get(i).label().ordinal();
}
model.update(x, y);
}
/** Returns {@code null} when no word of the ticket is in the vocabulary: the library would return a sentinel. */
@Override public Category predict(String text) {
return allZero(bow.apply(text)) ? null : Category.values()[rawPredict(text)];
}
/** Calls Smile directly. With no known words this returns {@link Integer#MIN_VALUE}, not a class index. */
public int rawPredict(String text) {
return model.predict(bow.apply(text));
}
public DiscreteNaiveBayes model() { return model; }
public Object[] shippable() { return new Object[] {model, vocab}; }
}
private static boolean allZero(int[] counts) {
for (int c : counts) if (c != 0) return false;
return true;
}
private static double[] toDouble(int[] counts) {
double[] d = new double[counts.length];
for (int i = 0; i < d.length; i++) d[i] = counts[i];
return d;
}
}
@@ -0,0 +1,60 @@
package com.ankurm.classicml;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/** Stratified train/test split, plus the duplicate check that keeps the split honest. */
public final class Splits {
public record Split(List<Ticket> train, List<Ticket> test) { }
private Splits() { }
/** Splits per category so every class keeps the same share in both halves. */
public static Split stratified(List<Ticket> all, double trainShare, long seed) {
Map<Category, List<Ticket>> byClass = new EnumMap<>(Category.class);
for (Ticket t : all) byClass.computeIfAbsent(t.label(), k -> new ArrayList<>()).add(t);
List<Ticket> train = new ArrayList<>();
List<Ticket> test = new ArrayList<>();
Random rnd = new Random(seed);
for (List<Ticket> group : byClass.values()) {
Collections.shuffle(group, rnd);
int cut = (int) Math.round(group.size() * trainShare);
train.addAll(group.subList(0, cut));
test.addAll(group.subList(cut, group.size()));
}
Collections.shuffle(train, rnd);
Collections.shuffle(test, rnd);
return new Split(train, test);
}
/** Lower-cases and collapses whitespace so "Hi team" and "hi team" count as the same ticket. */
public static String key(String text) {
return text.toLowerCase(Locale.ROOT).replaceAll("\\s+", " ").trim();
}
/** Test tickets whose normalised text also occurs in training: the model has already seen them. */
public static List<Ticket> testSeenInTraining(Split s) {
Set<String> seen = new HashSet<>();
for (Ticket t : s.train()) seen.add(key(t.text()));
List<Ticket> dup = new ArrayList<>();
for (Ticket t : s.test()) if (seen.contains(key(t.text()))) dup.add(t);
return dup;
}
/** Test tickets that never occur in training. */
public static List<Ticket> testUnseen(Split s) {
Set<String> seen = new HashSet<>();
for (Ticket t : s.train()) seen.add(key(t.text()));
List<Ticket> fresh = new ArrayList<>();
for (Ticket t : s.test()) if (!seen.contains(key(t.text()))) fresh.add(t);
return fresh;
}
}
@@ -0,0 +1,14 @@
package com.ankurm.classicml;
import java.util.List;
/** The one contract every contender implements, so the harness measures them identically. */
public interface TextClassifier {
String name();
void train(List<Ticket> train);
/** The category, or {@code null} when the model has no basis to answer (counted as wrong by {@link Metrics}). */
Category predict(String text);
}
@@ -0,0 +1,4 @@
package com.ankurm.classicml;
/** One support ticket: free text and the category a human assigned to it. */
public record Ticket(String text, Category label) { }
@@ -0,0 +1,180 @@
package com.ankurm.classicml;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* A seeded generator of synthetic support tickets. The data is fake on purpose: it makes every number in the post
* reproducible, and the knobs ({@link Options}) let the tests break the data in the ways real data breaks.
*
* <p>Real tickets are messier than these. Read the accuracy figures as "what the harness measures", never as
* "what you will get on your own tickets".
*/
public final class TicketGenerator {
/** Knobs for one dataset. {@code weights} are relative class frequencies. */
public record Options(long seed, int count, Map<Category, Double> weights,
double crossRate, double typoRate, double labelNoise, boolean drift) {
public static Options balanced(long seed, int count) {
Map<Category, Double> w = new EnumMap<>(Category.class);
for (Category c : Category.values()) w.put(c, 1.0);
return new Options(seed, count, w, 0.15, 0.12, 0.03, false);
}
public Options withWeights(Map<Category, Double> w) {
return new Options(seed, count, w, crossRate, typoRate, labelNoise, drift);
}
public Options withDrift(boolean d) {
return new Options(seed, count, weights, crossRate, typoRate, labelNoise, d);
}
public Options withSeed(long s) {
return new Options(s, count, weights, crossRate, typoRate, labelNoise, drift);
}
}
private static final Map<Category, List<String>> CORE = new EnumMap<>(Category.class);
private static final Map<Category, List<String>> DRIFTED = new EnumMap<>(Category.class);
static {
CORE.put(Category.BILLING, List.of(
"I was charged twice for this month",
"my invoice shows the wrong amount",
"please refund the duplicate payment",
"the card on file was declined but I was still billed",
"I need a GST invoice for last quarter",
"why did the price of my plan go up",
"my payment failed and the account shows overdue",
"there is a charge on my statement I do not recognise"));
CORE.put(Category.ACCESS, List.of(
"I cannot log in with my password",
"the reset password email never arrives",
"my account is locked after too many attempts",
"the two factor code is not accepted",
"I get logged out every few minutes",
"the single sign on page shows access denied",
"I lost the phone with my authenticator app",
"my invite link says it has expired"));
CORE.put(Category.BUG, List.of(
"the export button does nothing when I click it",
"the page crashes with an error when I save",
"the app freezes on the dashboard",
"search returns an empty list although the data exists",
"the report shows wrong totals after a refresh",
"uploading a file fails with error 500",
"the mobile app closes right after opening",
"notifications arrive twice for the same event"));
CORE.put(Category.FEATURE, List.of(
"it would be great to have a dark mode",
"please add an option to export to excel",
"can you support bulk edit for items",
"we need an api for webhooks",
"would you consider adding a calendar view",
"please allow custom fields on tickets",
"an option to schedule reports would help us",
"can you add support for single sign on"));
CORE.put(Category.CANCEL, List.of(
"I want to cancel my subscription",
"please close my account and delete my data",
"how do I stop the auto renewal",
"we are moving to another tool and will not renew",
"please downgrade me to the free plan",
"cancel my plan before the next billing date",
"I no longer need this service",
"end my trial without charging me"));
// Vocabulary the model never saw in training: new products and new words for old problems.
DRIFTED.put(Category.ACCESS, List.of(
"my passkey is not recognised on the new laptop",
"the magic link bounces back to the sign in page",
"device verification loops forever"));
DRIFTED.put(Category.BUG, List.of(
"the new editor glitches when I paste text",
"the widget flickers and then disappears",
"the sync spinner never stops"));
}
private static final List<String> OPENERS = List.of("Hi team,", "Hello,", "Urgent:", "Please help.", "", "Good morning,");
private static final List<String> CONTEXT = List.of(
"I am on the Pro plan.", "This started yesterday.", "I am using the mobile app.",
"I am using Chrome on Windows.", "My account email is on file.", "The order number ends 4471.", "", "");
private static final List<String> CLOSERS = List.of("Thanks.", "Please advise.", "Regards, Priya", "", "Thank you", "");
private TicketGenerator() { }
/** Generates {@code options.count()} tickets. The same options always produce the same list. */
public static List<Ticket> generate(Options o) {
Random rnd = new Random(o.seed());
Category[] cats = Category.values();
double total = 0;
for (Category c : cats) total += o.weights().getOrDefault(c, 0.0);
List<Ticket> out = new ArrayList<>(o.count());
for (int i = 0; i < o.count(); i++) {
Category label = pick(cats, o, total, rnd);
String core = corePhrase(label, o, rnd);
StringBuilder sb = new StringBuilder();
append(sb, OPENERS.get(rnd.nextInt(OPENERS.size())));
append(sb, capitalise(core) + ".");
if (rnd.nextDouble() < o.crossRate()) {
Category other = cats[rnd.nextInt(cats.length)];
if (other != label) append(sb, "Also, " + CORE.get(other).get(rnd.nextInt(8)) + ".");
}
append(sb, CONTEXT.get(rnd.nextInt(CONTEXT.size())));
append(sb, CLOSERS.get(rnd.nextInt(CLOSERS.size())));
String text = sb.toString().trim();
if (rnd.nextDouble() < o.typoRate()) text = typo(text, rnd);
Category recorded = label;
if (rnd.nextDouble() < o.labelNoise()) recorded = cats[rnd.nextInt(cats.length)];
out.add(new Ticket(text, recorded));
}
return out;
}
private static Category pick(Category[] cats, Options o, double total, Random rnd) {
double r = rnd.nextDouble() * total;
for (Category c : cats) {
r -= o.weights().getOrDefault(c, 0.0);
if (r <= 0) return c;
}
return cats[cats.length - 1];
}
private static String corePhrase(Category label, Options o, Random rnd) {
List<String> drifted = DRIFTED.get(label);
if (o.drift() && drifted != null) return drifted.get(rnd.nextInt(drifted.size()));
List<String> pool = CORE.get(label);
return pool.get(rnd.nextInt(pool.size()));
}
private static void append(StringBuilder sb, String part) {
if (part.isEmpty()) return;
if (!sb.isEmpty()) sb.append(' ');
sb.append(part);
}
private static String capitalise(String s) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
/** Swaps two adjacent letters inside one word, the commonest typing slip. */
private static String typo(String text, Random rnd) {
String[] words = text.split(" ");
int w = rnd.nextInt(words.length);
char[] c = words[w].toCharArray();
if (c.length >= 4) {
int k = 1 + rnd.nextInt(c.length - 2);
char t = c[k];
c[k] = c[k + 1];
c[k + 1] = t;
words[w] = new String(c);
}
return String.join(" ", words);
}
}
@@ -0,0 +1,17 @@
package com.ankurm.classicml;
import java.util.Locale;
import java.util.regex.Pattern;
/** Lower-cased word tokens, shared by every classic model so the comparison is about the library, not the tokeniser. */
public final class Tokens {
private static final Pattern NON_LETTER = Pattern.compile("[^a-z0-9]+");
private Tokens() { }
public static String[] of(String text) {
String t = NON_LETTER.matcher(text.toLowerCase(Locale.ROOT)).replaceAll(" ").trim();
return t.isEmpty() ? new String[0] : t.split(" ");
}
}
@@ -0,0 +1,72 @@
package com.ankurm.classicml;
import org.tribuo.Example;
import org.tribuo.MutableDataset;
import org.tribuo.Prediction;
import org.tribuo.classification.Label;
import org.tribuo.classification.LabelFactory;
import org.tribuo.classification.sgd.linear.LogisticRegressionTrainer;
import org.tribuo.data.text.TextFeatureExtractor;
import org.tribuo.data.text.impl.BasicPipeline;
import org.tribuo.data.text.impl.TextFeatureExtractorImpl;
import org.tribuo.provenance.SimpleDataSourceProvenance;
import org.tribuo.util.tokens.impl.BreakIteratorTokenizer;
import java.util.List;
import java.util.Locale;
/**
* Tribuo 4.3.2: text becomes {@link Example}s through a {@link BasicPipeline} (tokeniser plus n-gram size),
* and {@link LogisticRegressionTrainer} fits a multinomial logistic regression by SGD.
*/
public final class TribuoClassifier implements TextClassifier {
private final LabelFactory labels = new LabelFactory();
private final TextFeatureExtractor<Label> extractor =
new TextFeatureExtractorImpl<>(new BasicPipeline(new BreakIteratorTokenizer(Locale.US), 1));
private org.tribuo.Model<Label> model;
private MutableDataset<Label> trainingSet;
@Override public String name() { return "Tribuo LogisticRegression (SGD)"; }
@Override public void train(List<Ticket> train) {
trainingSet = dataset(train);
model = new LogisticRegressionTrainer().train(trainingSet);
}
/** Returns {@code null} when no word of the ticket was in the training vocabulary, because Tribuo refuses to guess. */
@Override public Category predict(String text) {
try {
return Category.valueOf(rawPredict(text));
} catch (IllegalArgumentException noKnownFeatures) {
return null;
}
}
/** Calls Tribuo directly. Throws {@link IllegalArgumentException} ("No features found in Example") on unknown words. */
public String rawPredict(String text) {
Prediction<Label> p = model.predict(extractor.extract(new Label(Label.UNKNOWN), normalise(text)));
return p.getOutput().getLabel();
}
/** The trained Tribuo model, for the evaluator cross-check and for serialisation size. */
public org.tribuo.Model<Label> model() { return model; }
/** Builds a Tribuo dataset from tickets; the evaluator needs this form for the test set. */
public MutableDataset<Label> dataset(List<Ticket> tickets) {
MutableDataset<Label> ds = new MutableDataset<>(new SimpleDataSourceProvenance("tickets", labels), labels);
for (Ticket t : tickets) {
ds.add(extractor.extract(new Label(t.label().name()), normalise(t.text())));
}
return ds;
}
/**
* Hands Tribuo exactly the tokens the Smile models see. Left alone, {@code BasicPipeline} with a
* {@code BreakIteratorTokenizer} turns "." "," and "!" into features, which would make the comparison unfair.
*/
private static String normalise(String text) {
return String.join(" ", Tokens.of(text));
}
}
@@ -0,0 +1,87 @@
package com.ankurm.classicml;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A zero-shot classifier over any OpenAI-compatible {@code /v1/chat/completions} endpoint (a hosted API, Ollama,
* vLLM, llama.cpp). It sends the instruction and the ticket, and refuses to guess when the reply is not exactly
* one known category.
*/
public final class ZeroShotLlm {
private static final Pattern CONTENT = Pattern.compile("\"content\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private final String baseUrl;
private final String model;
private final String apiKey;
public ZeroShotLlm(String baseUrl, String model, String apiKey) {
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
this.model = model;
this.apiKey = apiKey;
}
/** The category the model chose, or empty when the reply was not exactly one known category. */
public Optional<Category> classify(String ticketText) throws IOException, InterruptedException {
String body = "{\"model\":\"" + esc(model) + "\",\"temperature\":0,\"max_tokens\":8,\"messages\":["
+ "{\"role\":\"system\",\"content\":\"" + esc(ZeroShotPrompt.SYSTEM) + "\"},"
+ "{\"role\":\"user\",\"content\":\"" + esc(ZeroShotPrompt.user(ticketText)) + "\"}]}";
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(baseUrl + "/v1/chat/completions"))
.timeout(Duration.ofSeconds(60))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body));
if (apiKey != null && !apiKey.isBlank()) req.header("Authorization", "Bearer " + apiKey);
HttpResponse<String> res = http.send(req.build(), HttpResponse.BodyHandlers.ofString());
if (res.statusCode() != 200) throw new IOException("HTTP " + res.statusCode() + ": " + res.body());
Matcher m = CONTENT.matcher(res.body());
return m.find() ? parse(unesc(m.group(1))) : Optional.empty();
}
/**
* Accepts a reply only when exactly one category name appears in it, ignoring case and punctuation.
* "Billing." is accepted; "It could be BILLING or CANCEL" and "I think this is a refund" are not.
*/
public static Optional<Category> parse(String reply) {
Set<Category> found = EnumSet.noneOf(Category.class);
String upper = reply.toUpperCase();
for (Category c : Category.values()) {
if (Pattern.compile("\\b" + c.name() + "\\b").matcher(upper).find()) found.add(c);
}
return found.size() == 1 ? Optional.of(found.iterator().next()) : Optional.empty();
}
/** Scores a test set; a reply that cannot be parsed counts as wrong, never as a guess. */
public Score score(List<Ticket> test) throws IOException, InterruptedException {
int right = 0, unparseable = 0;
for (Ticket t : test) {
Optional<Category> c = classify(t.text());
if (c.isEmpty()) unparseable++;
else if (c.get() == t.label()) right++;
}
return new Score(test.size(), right, unparseable);
}
public record Score(int total, int right, int unparseable) {
public double accuracy() { return total == 0 ? 0 : (double) right / total; }
}
private static String esc(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
}
private static String unesc(String s) {
return s.replace("\\n", "\n").replace("\\\"", "\"").replace("\\\\", "\\");
}
}
@@ -0,0 +1,30 @@
package com.ankurm.classicml;
import java.util.Arrays;
import java.util.stream.Collectors;
/** The zero-shot instruction, built once, and a rough token estimate for it. */
public final class ZeroShotPrompt {
public static final String SYSTEM =
"You classify customer support tickets. Reply with exactly one word from this list and nothing else: "
+ Arrays.stream(Category.values()).map(Enum::name).collect(Collectors.joining(", "))
+ ". BILLING is about charges, invoices and refunds. ACCESS is about login, passwords and locked accounts. "
+ "BUG is about something that is broken. FEATURE is a request for something new. "
+ "CANCEL is about ending a subscription or account.";
private ZeroShotPrompt() { }
public static String user(String ticketText) {
return "Ticket: " + ticketText + "\nCategory:";
}
/** About four characters per English token. An estimate, not a tokeniser: real counts differ by model. */
public static int estimateTokens(String text) {
return (int) Math.ceil(text.length() / 4.0);
}
public static int estimatePromptTokens(String ticketText) {
return estimateTokens(SYSTEM) + estimateTokens(user(ticketText));
}
}
@@ -0,0 +1,38 @@
package com.ankurm.classicml;
import org.junit.jupiter.api.Test;
import java.io.DataInputStream;
import java.io.InputStream;
import static org.assertj.core.api.Assertions.assertThat;
/** Reads the class-file version out of one class from each library, so "needs Java N" is measured, not remembered. */
class ClassFileVersionTest {
@Test
void whichJavaDoesEachLibraryNeed() throws Exception {
int tribuo = major("org/tribuo/Model.class");
int smile = major("smile/classification/Maxent.class");
Transcript t = new Transcript("10-class-file-versions.txt", "The Java version each library's bytecode needs");
t.line("class-file major version 52 = Java 8, 61 = Java 17, 65 = Java 21, 69 = Java 25");
t.blank();
t.line("Tribuo 4.3.2 org.tribuo.Model major " + tribuo + " (Java " + (tribuo - 44) + ")");
t.line("Smile 7.3.0 smile.classification.Maxent major " + smile + " (Java " + (smile - 44) + ")");
t.write();
assertThat(tribuo).isEqualTo(52);
assertThat(smile).isEqualTo(69);
}
private static int major(String resource) throws Exception {
try (InputStream in = ClassLoader.getSystemResourceAsStream(resource)) {
assertThat(in).as(resource).isNotNull();
DataInputStream d = new DataInputStream(in);
d.readInt(); // magic
d.readUnsignedShort(); // minor
return d.readUnsignedShort();
}
}
}
@@ -0,0 +1,44 @@
package com.ankurm.classicml;
import org.junit.jupiter.api.Test;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
class CostModelTest {
@Test
void theFormulaForAMillionTickets() throws Exception {
double promptTokens = Fixtures.SPLIT.test().stream()
.mapToInt(k -> ZeroShotPrompt.estimatePromptTokens(k.text())).average().orElseThrow();
double outputTokens = 3;
double tribuoMicros = Fixtures.R_TRIBUO.medianMicros();
double coreHour = 0.05;
Transcript t = new Transcript("09-cost-model.txt", "What a million tickets cost: a formula, not a price list");
t.line("EVERY PRICE BELOW IS AN ASSUMPTION. Replace the three rate cards with the ones you actually pay.");
t.line(String.format(Locale.ROOT, "inputs: %.1f prompt tokens per ticket (estimate), %.0f output tokens, 1,000,000 tickets", promptTokens, outputTokens));
t.blank();
t.section("LLM, billed per token (output priced at 5x input in every row)");
t.line(String.format(Locale.ROOT, "%-34s %14s", "assumed $ per 1M input tokens", "$ per 1M tickets"));
double last = 0;
for (double in : new double[] {0.10, 1.00, 3.00}) {
double d = CostModel.llmDollars(1_000_000, promptTokens, outputTokens, in, in * 5);
t.line(String.format(Locale.ROOT, "%-34s %14.2f", String.format(Locale.ROOT, "%.2f", in), d));
assertThat(d).isGreaterThan(last);
last = d;
}
t.section("Classic model, in-process on one CPU core");
double cpu = CostModel.cpuDollars(1_000_000, tribuoMicros, coreHour);
t.line(String.format(Locale.ROOT, "measured median predict (Tribuo, 02-models.txt run): %.1f microseconds", tribuoMicros));
t.line(String.format(Locale.ROOT, "assumed core price: $%.2f per core-hour", coreHour));
t.line(String.format(Locale.ROOT, "core-seconds for 1M tickets: %.1f cost: $%.4f", 1_000_000 * tribuoMicros / 1e6, cpu));
t.blank();
t.line("Not in either number: training and labelling for the classic model, retries and rate limits for the LLM,");
t.line("and the engineer-hours for both. They usually decide the real comparison.");
t.write();
assertThat(cpu).isLessThan(CostModel.llmDollars(1_000_000, promptTokens, outputTokens, 0.10, 0.50));
}
}
@@ -0,0 +1,48 @@
package com.ankurm.classicml;
import com.ankurm.classicml.TicketGenerator.Options;
import org.junit.jupiter.api.Test;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Map;
import static com.ankurm.classicml.Fixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
class DatasetTest {
@Test
void theDatasetIsReproducibleAndSplitHonestly() throws Exception {
assertThat(TicketGenerator.generate(Options.balanced(42, 3000))).isEqualTo(ALL);
assertThat(TicketGenerator.generate(Options.balanced(43, 3000))).isNotEqualTo(ALL);
Transcript t = new Transcript("01-dataset.txt", "The synthetic ticket set and its split");
t.line("generator: seed 42, 3000 tickets, 15% carry a second complaint from another class, 12% have a typo,");
t.line("3% have a randomly wrong label (human labelling noise)");
t.section("Class counts");
t.line(String.format(Locale.ROOT, "%-9s %6s %6s", "class", "train", "test"));
for (Category c : Category.values()) {
t.line(String.format(Locale.ROOT, "%-9s %6d %6d", c, count(SPLIT.train(), c), count(SPLIT.test(), c)));
}
t.line(String.format(Locale.ROOT, "%-9s %6d %6d", "total", SPLIT.train().size(), SPLIT.test().size()));
t.section("Exact duplicates between train and test");
int seen = Splits.testSeenInTraining(SPLIT).size();
t.line("test tickets whose normalised text also appears in train: " + seen + " of " + SPLIT.test().size());
t.section("Six tickets, first six of the test set");
for (int i = 0; i < 6; i++) {
Ticket k = SPLIT.test().get(i);
t.line(String.format(Locale.ROOT, "%-8s | %s", k.label(), k.text()));
}
t.write();
assertThat(SPLIT.train().size() + SPLIT.test().size()).isEqualTo(3000);
assertThat(seen).isGreaterThan(0);
}
private static long count(java.util.List<Ticket> l, Category c) {
return l.stream().filter(k -> k.label() == c).count();
}
}
@@ -0,0 +1,66 @@
package com.ankurm.classicml;
import com.ankurm.classicml.TicketGenerator.Options;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
/** One balanced dataset and one training run per contender, shared by every test class in the JVM. */
final class Fixtures {
static final List<Ticket> ALL = TicketGenerator.generate(Options.balanced(42, 3000));
static final Splits.Split SPLIT = Splits.stratified(ALL, 0.8, 7);
static final TribuoClassifier TRIBUO = new TribuoClassifier();
static final SmileClassifiers.Logistic SMILE_LR = new SmileClassifiers.Logistic();
static final SmileClassifiers.NaiveBayes SMILE_NB = new SmileClassifiers.NaiveBayes();
static final MajorityBaseline BASELINE = new MajorityBaseline();
static final Run R_BASE = run(BASELINE, SPLIT);
static final Run R_TRIBUO = run(TRIBUO, SPLIT);
static final Run R_SMILE_LR = run(SMILE_LR, SPLIT);
static final Run R_SMILE_NB = run(SMILE_NB, SPLIT);
private Fixtures() { }
/** One contender trained and timed. Timings vary between runs and machines; accuracy does not. */
record Run(TextClassifier model, long trainMillis, double medianMicros, double p99Micros, Metrics metrics) { }
static Run run(TextClassifier model, Splits.Split s) {
long t0 = System.nanoTime();
model.train(s.train());
long trainMs = (System.nanoTime() - t0) / 1_000_000;
// Warm the JIT first so the numbers describe steady state, which is what a service sees.
for (int i = 0; i < 300; i++) model.predict(s.test().get(i % s.test().size()).text());
double[] us = new double[s.test().size()];
for (int i = 0; i < us.length; i++) {
long a = System.nanoTime();
model.predict(s.test().get(i).text());
us[i] = (System.nanoTime() - a) / 1000.0;
}
Arrays.sort(us);
return new Run(model, trainMs, us[us.length / 2], us[(int) (us.length * 0.99)], Metrics.of(model, s.test()));
}
/** Bytes of the artefact you would deploy. Tribuo writes its own protobuf format; Smile uses Java serialisation. */
static long modelBytes(Object shippableOrTribuoModel) throws Exception {
if (shippableOrTribuoModel instanceof org.tribuo.Model<?> m) {
Path f = Files.createTempFile("tribuo", ".model");
try {
m.serializeToFile(f);
return Files.size(f);
} finally {
Files.deleteIfExists(f);
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(shippableOrTribuoModel);
}
return bos.size();
}
}
@@ -0,0 +1,87 @@
package com.ankurm.classicml;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the zero-shot client against a local fake endpoint. This proves the wiring and the reply guard. It says
* nothing about how accurate any real model is: no model was called while this module was written.
*/
class LlmHarnessTest {
@Test
void theReplyGuardAcceptsOneCategoryAndNothingElse() throws Exception {
Transcript t = new Transcript("08-llm-harness.txt", "Zero-shot client against a fake endpoint (wiring only, no model)");
t.line("NO LLM WAS CALLED. A local server returns scripted replies, so this shows request shape and reply handling.");
String[][] replies = {
{"BILLING", "accepted"}, {"Access.", "accepted"}, {"The category is Bug", "accepted"},
{"BILLING or CANCEL", "rejected: two categories"}, {"I think this is a refund request", "rejected: no category name"},
{"", "rejected: empty"}};
t.section("Reply guard, ZeroShotLlm.parse");
for (String[] r : replies) {
Optional<Category> c = ZeroShotLlm.parse(r[0]);
t.line(String.format("%-34s -> %-9s (%s)", "\"" + r[0] + "\"", c.map(Enum::name).orElse("(none)"), r[1]));
assertThat(c.isPresent()).isEqualTo(r[1].startsWith("accepted"));
}
Deque<String> script = new ArrayDeque<>(List.of("BILLING", "ACCESS", "Probably BUG.", "FEATURE or BILLING", "CANCEL"));
List<String> bodies = new ArrayList<>();
List<String> auth = new ArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/v1/chat/completions", ex -> {
bodies.add(new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
auth.add(ex.getRequestHeaders().getFirst("Authorization"));
byte[] out = ("{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"" + script.poll() + "\"}}]}")
.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, out.length);
ex.getResponseBody().write(out);
ex.close();
});
server.start();
try {
ZeroShotLlm llm = new ZeroShotLlm("http://127.0.0.1:" + server.getAddress().getPort(), "any-model", "test-key");
List<Ticket> five = List.of(
new Ticket("I was charged twice for this month.", Category.BILLING),
new Ticket("The reset password email never arrives.", Category.ACCESS),
new Ticket("The app freezes on the dashboard.", Category.BUG),
new Ticket("Please add an option to export to excel.", Category.FEATURE),
new Ticket("I want to cancel my subscription.", Category.CANCEL));
ZeroShotLlm.Score s = llm.score(five);
t.section("Five scripted replies through the real HTTP client");
t.line("scripted: BILLING, ACCESS, Probably BUG., FEATURE or BILLING, CANCEL");
t.line("right " + s.right() + " of " + s.total() + ", unparseable " + s.unparseable()
+ " (the ambiguous reply counts as wrong, never as a guess)");
t.section("The first request body, verbatim");
t.line(bodies.get(0));
t.line("Authorization header: " + auth.get(0));
assertThat(s.right()).isEqualTo(4);
assertThat(s.unparseable()).isEqualTo(1);
assertThat(bodies.get(0)).contains("\"temperature\":0").contains("Ticket: I was charged twice");
assertThat(auth.get(0)).isEqualTo("Bearer test-key");
} finally {
server.stop(0);
}
t.section("Prompt size across the real test tickets (estimate: characters / 4)");
double avg = Fixtures.SPLIT.test().stream().mapToInt(k -> ZeroShotPrompt.estimatePromptTokens(k.text())).average().orElseThrow();
t.line("instruction alone : " + ZeroShotPrompt.estimateTokens(ZeroShotPrompt.SYSTEM) + " tokens");
t.line(String.format("average per ticket : %.1f tokens (instruction + ticket)", avg));
t.write();
assertThat(avg).isBetween(60.0, 140.0);
}
}
@@ -0,0 +1,62 @@
package com.ankurm.classicml;
import org.junit.jupiter.api.Test;
import org.tribuo.classification.evaluation.LabelEvaluation;
import org.tribuo.classification.evaluation.LabelEvaluator;
import java.util.Locale;
import static com.ankurm.classicml.Fixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
class ModelsTest {
@Test
void contendersOnTheBalancedSplit() throws Exception {
Transcript t = new Transcript("02-models.txt", "Three classic classifiers and a baseline on the same split");
t.line("dataset: 3000 synthetic tickets, " + SPLIT.train().size() + " train / " + SPLIT.test().size() + " test, 5 balanced classes (see 01-dataset.txt)");
t.line("timings are from one run on one machine and drift between runs; accuracy and F1 do not");
t.blank();
t.line(String.format(Locale.ROOT, "%-34s %8s %9s %9s %11s %9s %10s",
"model", "accuracy", "macro-F1", "train ms", "median us", "p99 us", "model KB"));
Object[][] rows = {
{R_BASE, null},
{R_TRIBUO, TRIBUO.model()},
{R_SMILE_LR, SMILE_LR.shippable()},
{R_SMILE_NB, SMILE_NB.shippable()}};
for (Object[] row : rows) {
Run r = (Run) row[0];
String kb = row[1] == null ? "-" : String.format(Locale.ROOT, "%.1f", modelBytes(row[1]) / 1024.0);
t.line(String.format(Locale.ROOT, "%-34s %8.4f %9.4f %9d %11.1f %9.1f %10s",
r.model().name(), r.metrics().accuracy(), r.metrics().macroF1(),
r.trainMillis(), r.medianMicros(), r.p99Micros(), kb));
}
t.section("Tribuo's own evaluator against ours");
LabelEvaluation ev = new LabelEvaluator().evaluate(TRIBUO.model(), TRIBUO.dataset(SPLIT.test()));
t.line(String.format(Locale.ROOT, "Tribuo LabelEvaluator accuracy : %.4f", ev.accuracy()));
t.line(String.format(Locale.ROOT, "harness Metrics accuracy : %.4f", R_TRIBUO.metrics().accuracy()));
t.line(String.format(Locale.ROOT, "Tribuo LabelEvaluator macro F1 : %.4f", ev.macroAveragedF1()));
t.line(String.format(Locale.ROOT, "harness Metrics macro F1 : %.4f", R_TRIBUO.metrics().macroF1()));
t.write();
Transcript c = new Transcript("03-confusion-tribuo.txt", "Tribuo logistic regression: where the mistakes go");
c.line("rows are the true category, columns the predicted one");
c.blank();
c.line(R_TRIBUO.metrics().confusionTable());
c.blank();
for (Category cat : Category.values()) {
c.line(String.format(Locale.ROOT, "%-8s precision %.3f recall %.3f F1 %.3f", cat,
R_TRIBUO.metrics().precision(cat), R_TRIBUO.metrics().recall(cat), R_TRIBUO.metrics().f1(cat)));
}
c.write();
assertThat(R_BASE.metrics().accuracy()).isLessThan(0.30);
for (Run r : new Run[] {R_TRIBUO, R_SMILE_LR, R_SMILE_NB}) {
assertThat(r.metrics().accuracy()).isGreaterThan(0.85);
assertThat(r.metrics().macroF1()).isGreaterThan(R_BASE.metrics().macroF1() + 0.5);
}
assertThat(ev.accuracy()).isCloseTo(R_TRIBUO.metrics().accuracy(), within(1e-9));
}
}
@@ -0,0 +1,46 @@
package com.ankurm.classicml;
import org.junit.jupiter.api.Test;
import java.util.Locale;
import static com.ankurm.classicml.Fixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** What each library does with a ticket whose words it has never seen. The three answers are all different. */
class NoKnownWordsTest {
private static final String UNSEEN = "Device verification loops forever.";
@Test
void threeLibrariesThreeBehaviours() throws Exception {
Transcript t = new Transcript("07-no-known-words.txt", "A ticket made only of words the model has never seen");
t.line("input: \"" + UNSEEN + "\" (none of these words occur in the training tickets)");
t.blank();
String tribuo;
try {
tribuo = TRIBUO.rawPredict(UNSEEN);
} catch (IllegalArgumentException e) {
tribuo = "throws IllegalArgumentException: " + e.getMessage().replaceAll("ArrayExample.*", "ArrayExample(...)");
}
int lr = SMILE_LR.rawPredict(UNSEEN);
int nb = SMILE_NB.rawPredict(UNSEEN);
t.line("Tribuo LogisticRegression raw : " + tribuo);
t.line("Smile LogisticRegression raw : returns class index " + lr + " (" + Category.values()[lr] + "), a guess from the intercepts alone");
t.line("Smile DiscreteNaiveBayes raw : returns " + nb + " (Integer.MIN_VALUE, not a class index)");
t.blank();
t.line("harness wrappers (predict) : " + TRIBUO.predict(UNSEEN) + " / " + SMILE_LR.predict(UNSEEN) + " / " + SMILE_NB.predict(UNSEEN)
+ " (null = no answer, counted as wrong)");
t.write();
assertThatThrownBy(() -> TRIBUO.rawPredict(UNSEEN)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No features found");
assertThat(nb).isEqualTo(Integer.MIN_VALUE);
assertThat(lr).isBetween(0, Category.values().length - 1);
assertThat(TRIBUO.predict(UNSEEN)).isNull();
assertThat(SMILE_LR.predict(UNSEEN)).isNull();
assertThat(SMILE_NB.predict(UNSEEN)).isNull();
}
}
@@ -0,0 +1,91 @@
package com.ankurm.classicml;
import com.ankurm.classicml.TicketGenerator.Options;
import org.junit.jupiter.api.Test;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.ankurm.classicml.Fixtures.Run;
import static com.ankurm.classicml.Fixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
/** Three ways a good-looking number goes wrong. Each test records the evidence in output/. */
class PitfallsTest {
@Test
void accuracyLiesWhenClassesAreSkewed() throws Exception {
Map<Category, Double> w = new EnumMap<>(Category.class);
w.put(Category.BILLING, 0.55);
w.put(Category.ACCESS, 0.25);
w.put(Category.BUG, 0.12);
w.put(Category.FEATURE, 0.06);
w.put(Category.CANCEL, 0.02);
List<Ticket> skewed = TicketGenerator.generate(Options.balanced(11, 3000).withWeights(w));
Splits.Split s = Splits.stratified(skewed, 0.8, 7);
Run base = Fixtures.run(new MajorityBaseline(), s);
Run tribuo = Fixtures.run(new TribuoClassifier(), s);
Transcript t = new Transcript("04-imbalance.txt", "Skewed classes: accuracy against macro-F1");
t.line("class mix 55% BILLING, 25% ACCESS, 12% BUG, 6% FEATURE, 2% CANCEL; " + s.train().size() + " train / " + s.test().size() + " test");
t.blank();
t.line(String.format(Locale.ROOT, "%-34s %8s %9s %14s", "model", "accuracy", "macro-F1", "CANCEL recall"));
for (Run r : new Run[] {base, tribuo}) {
t.line(String.format(Locale.ROOT, "%-34s %8.4f %9.4f %14.3f", r.model().name(),
r.metrics().accuracy(), r.metrics().macroF1(), r.metrics().recall(Category.CANCEL)));
}
t.write();
// A model that always says BILLING scores above 50% accuracy and has a macro-F1 near 0.14.
assertThat(base.metrics().accuracy()).isGreaterThan(0.5);
assertThat(base.metrics().macroF1()).isLessThan(0.2);
assertThat(tribuo.metrics().macroF1()).isGreaterThan(0.8);
}
@Test
void duplicatesInTheTestSetFlatterTheModel() throws Exception {
Run r = R_TRIBUO;
List<Ticket> seen = Splits.testSeenInTraining(SPLIT);
List<Ticket> fresh = Splits.testUnseen(SPLIT);
double accSeen = acc(r.model(), seen), accFresh = acc(r.model(), fresh);
Transcript t = new Transcript("05-duplicates.txt", "Tickets the model has already seen");
t.line("Tribuo logistic regression, balanced split from 02-models.txt");
t.blank();
t.line(String.format(Locale.ROOT, "test tickets also in train : %4d accuracy %.4f", seen.size(), accSeen));
t.line(String.format(Locale.ROOT, "test tickets never seen : %4d accuracy %.4f", fresh.size(), accFresh));
t.line(String.format(Locale.ROOT, "whole test set : %4d accuracy %.4f", SPLIT.test().size(), r.metrics().accuracy()));
t.write();
assertThat(seen.size() + fresh.size()).isEqualTo(SPLIT.test().size());
assertThat(accSeen).isGreaterThanOrEqualTo(accFresh);
}
@Test
void newVocabularyBreaksAClassicModelAndTheNumbersShowIt() throws Exception {
List<Ticket> drifted = TicketGenerator.generate(Options.balanced(99, 1000).withDrift(true));
Transcript t = new Transcript("06-vocabulary-drift.txt", "Tickets that use words the model never saw");
t.line("trained on the balanced set; tested on 1000 new tickets where ACCESS and BUG use new wording");
t.line("(passkey, magic link, device verification, editor glitches, widget flickers, sync spinner)");
t.blank();
t.line(String.format(Locale.ROOT, "%-34s %9s %9s %12s %12s", "model", "normal", "drifted", "ACCESS rec.", "BUG rec."));
double tribuoNormal = 0, tribuoDrift = 0;
for (Run r : new Run[] {R_TRIBUO, R_SMILE_LR, R_SMILE_NB}) {
Metrics m = Metrics.of(r.model(), drifted);
t.line(String.format(Locale.ROOT, "%-34s %9.4f %9.4f %12.3f %12.3f", r.model().name(),
r.metrics().accuracy(), m.accuracy(), m.recall(Category.ACCESS), m.recall(Category.BUG)));
if (r.model() == TRIBUO) { tribuoNormal = r.metrics().accuracy(); tribuoDrift = m.accuracy(); }
}
t.write();
assertThat(tribuoDrift).isLessThan(tribuoNormal - 0.05);
}
private static double acc(TextClassifier m, List<Ticket> tickets) {
return Metrics.of(m, tickets).accuracy();
}
}
@@ -0,0 +1,41 @@
package com.ankurm.classicml;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects lines and writes {@code output/NN-name.txt}, so the test that asserts a fact is the test that records it. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String file;
Transcript(String file, String title) {
this.file = file;
lines.add("# " + title);
}
Transcript line(String s) {
lines.add(s);
return this;
}
Transcript blank() {
lines.add("");
return this;
}
Transcript section(String s) {
lines.add("");
lines.add("## " + s);
return this;
}
void write() throws IOException {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.write(dir.resolve(file), lines);
}
}
+30
View File
@@ -0,0 +1,30 @@
# log-anomaly
Log anomaly detection for a Spring Boot application, in plain Java 25 and Spring Boot 4.2.0. A baseline log is parsed,
reduced to message templates, embedded, and grouped with k-means. A new log is then checked two ways: a template that
never occurred and is far from every normal cluster is a **novel template**; a template that did occur but arrives far
above its baseline rate is a **rate spike**. Findings that overlap in time become one incident with a short summary.
```bash
export JAVA_HOME=/path/to/jdk-25
mvn test -pl log-anomaly # writes output/01..12 (00 is the QuickStart run)
bash log-anomaly/scripts/run-all.sh # also packages the jar and writes output/13 with curl
java log-anomaly/quickstart/QuickStart.java # the whole idea in one file, no Maven
```
| Class | Role |
|---|---|
| `LogParser`, `LogEvent` | Spring Boot's default layout, with or without the application name; stack traces folded into one event |
| `TemplateMiner` | masks numbers and ids; an optional second pass wildcards words that vary (user names) |
| `Embedder`, `HashingEmbedder`, `OpenAiCompatibleEmbedder` | the seam: offline word hashing, or any `/v1/embeddings` endpoint |
| `KMeans`, `BaselineModel` | spherical k-means over baseline templates; distance = 1 - cosine to the nearest centre |
| `AnomalyDetector`, `Finding` | the novel-template and rate-spike detectors |
| `IncidentBuilder`, `Incident` | findings close in time become one incident |
| `IncidentSummarizer`, `TemplateSummarizer`, `LlmSummarizer` | a no-model summary, and a chat-endpoint summary that is sent templates, never raw lines |
| `SyntheticLogs`, `SampleLogWriter` | the seeded generator behind the tests (synthetic: see the class Javadoc) |
| `AnalysisService`, `AnomalyController`, `LogAnomalyApplication` | `GET /api/incidents?baseline=&target=` (demo only, it reads any path the server can read) |
`output/` holds the transcripts the tests write; every figure in the post is quoted from there. Files 12 and 13 contain
timestamps and process ids that change on every run. The hashing embedder compares words, not meaning, so the numbers
in `output/03` and `output/04` describe that embedder only. `OpenAiCompatibleEmbedder` and `LlmSummarizer` were tested
against stub servers and have not been run against a real model.
+10
View File
@@ -0,0 +1,10 @@
$ java QuickStart.java
normal lines: 6, normal templates: 4
Order <*> placed by customer c-<*>
Payment approved for order <*> in <*> ms
Reserved <*> units of SKU-<*>
Token validated for user u-<*>
0.000 known template Order <*> placed by customer c-<*>
0.764 NEW and FAR from normal HikariPool-<*> - Connection is not available, request timed out after <*>ms.
0.225 new but close to normal Payment approved for order <*> in <*> ms but ledger write failed
+21
View File
@@ -0,0 +1,21 @@
# Parsing Spring Boot log lines
## First lines of the baseline
2026-11-30T09:00:00.000+05:30 INFO 4121 --- [shop] [nio-8080-exec-6] c.a.shop.CatalogController : GET /api/products/884 200 in 13 ms
2026-11-30T09:00:01.843+05:30 INFO 4121 --- [shop] [nio-8080-exec-6] c.a.shop.OrderController : Order 77525 placed by customer c-519 total=8093.82
2026-11-30T09:00:03.687+05:30 INFO 4121 --- [shop] [nio-8080-exec-4] c.a.shop.CatalogController : GET /api/products/476 200 in 35 ms
## An ERROR with a stack trace: one event, several physical lines
2026-11-30T11:12:30.421+05:30 ERROR 4121 --- [shop] [nio-8080-exec-8] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Connection is not available, request timed out after 30000ms.
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:686)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:179)
## Counts
baseline: 3947 physical lines, 3857 events, 0 orphan lines
target: 2196 physical lines, 1524 events, 0 orphan lines
that ERROR event: level=ERROR logger=HikariPool continuation lines=3
exception line: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
## The same line without the application name bracket
parsed: level=INFO thread=nio-8080-exec-1 logger=OrderController message=Order 42 placed
+20
View File
@@ -0,0 +1,20 @@
# Template mining
## Baseline: 3857 events become 10 templates
791 INFO CatalogController GET /api/products/<*> <*> in <*> ms
746 INFO AuthFilter Token validated for user u-<*>
715 INFO OrderController Order <*> placed by customer c-<*> total=<*>
695 INFO InventoryService Reserved <*> units of SKU-<*>
653 INFO PaymentService Payment approved for order <*> in <*> ms
120 INFO HikariPool HikariPool-<*> - Pool stats (total=<*>, active=<*>, idle=<*>, waiting=<*>)
62 WARN PaymentService Payment declined for order <*>: insufficient funds
43 WARN SlowQueryDetector Slow query (<*> ms): select * from orders where customer_id = ?
30 ERROR OrderController Failed to process order <*>: validation failed
2 INFO CacheRefresher Nightly cache refresh completed in <*> ms
## Failure: words that are not numbers. Same traffic, real user names instead of u-1042
AuthFilter templates, digits-only masking: 20
AuthFilter templates, with the second pass: 1
all templates, digits-only masking: 29
all templates, with the second pass: 10
746 Token validated for user <*>
+21
View File
@@ -0,0 +1,21 @@
# What a hashing embedder considers close (distance = 1 - cosine)
distance 0.415
A: WARN PaymentService Payment declined for order <*>: insufficient funds
B: INFO PaymentService Payment approved for order <*> in <*> ms
distance 0.249
A: ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection
B: ERROR OrderController Failed to process order <*>: validation failed
distance 0.853
A: ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection
B: ERROR HikariPool Could not get a database connection from the pool
distance 0.118
A: INFO PaymentService Payment approved for order <*> in <*> ms
B: INFO PaymentService Payment approved for order <*> in <*> ms but ledger write failed
distance 1.000
A: INFO AuthFilter Token validated for user u-<*>
B: ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms.
+25
View File
@@ -0,0 +1,25 @@
# k decides how far from normal a template can be
## Baseline templates grouped with k = 4
cluster 0:
INFO CatalogController GET /api/products/<*> <*> in <*> ms (distance to centre 0.325)
INFO InventoryService Reserved <*> units of SKU-<*> (distance to centre 0.325)
INFO CacheRefresher Nightly cache refresh completed in <*> ms (distance to centre 0.321)
cluster 1:
INFO OrderController Order <*> placed by customer c-<*> total=<*> (distance to centre 0.343)
INFO PaymentService Payment approved for order <*> in <*> ms (distance to centre 0.212)
WARN PaymentService Payment declined for order <*>: insufficient funds (distance to centre 0.315)
ERROR OrderController Failed to process order <*>: validation failed (distance to centre 0.339)
cluster 2:
INFO AuthFilter Token validated for user u-<*> (distance to centre 0.239)
INFO HikariPool HikariPool-<*> - Pool stats (total=<*>, active=<*>, idle=<*>, waiting=<*>) (distance to centre 0.239)
cluster 3:
WARN SlowQueryDetector Slow query (<*> ms): select * from orders where customer_id = ? (distance to centre 0.000)
## Distance of the five new templates, and the threshold, for different k (threshold = worst baseline distance + 0.05)
k worst-normal threshold | hikari jdbc gateway reword ledger-fail
1 0.677 0.727 | 0.747* 0.629 0.623 0.470 0.368
2 0.564 0.614 | 0.726* 0.477 0.471 0.410 0.305
4 0.343 0.393 | 0.678* 0.434* 0.459* 0.394* 0.256
10 0.000 0.050 | 0.510* 0.249* 0.401* 0.101* 0.118*
(* = flagged at that threshold)
+18
View File
@@ -0,0 +1,18 @@
# Findings for the 30-minute target window (incident starts at minute 12)
threshold 0.393 (worst baseline distance 0.343 + margin 0.05), k = 4
## Flagged
NOVEL_TEMPLATE ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms. x144 new template, distance 0.678 > 0.393
NOVEL_TEMPLATE WARN PaymentService Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> x90 new template, distance 0.459 > 0.393
NOVEL_TEMPLATE ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection x108 new template, distance 0.434 > 0.393
NOVEL_TEMPLATE INFO OrderController Order <*> placed by customer c-<*> total=<*> currency=INR x156 new template, distance 0.394 > 0.393
RATE_SPIKE WARN PaymentService Payment declined for order <*>: insufficient funds x44 peak 44 per 5 min vs baseline mean 2.6 (std 0.9), z = 45.6
## Not flagged, although something is wrong
pool stats template known to the baseline: true
during the incident: HikariPool-1 - Pool stats (total=10, active=10, idle=0, waiting=32)
during normal times: HikariPool-1 - Pool stats (total=10, active=2, idle=8, waiting=0)
'but ledger write failed' has distance 0.256, threshold 0.393, so it is NOT flagged
## Flagged, although nothing is wrong
the deployment's reworded order line has distance 0.394 against threshold 0.393
+11
View File
@@ -0,0 +1,11 @@
# What each margin flags, k = 4
worst baseline distance: 0.343
margin 0.00 -> threshold 0.343 -> 4 of 5 new templates flagged: Order <*> | HikariPool-<*> - | Failed to | Payment gateway
margin 0.05 -> threshold 0.393 -> 4 of 5 new templates flagged: Order <*> | HikariPool-<*> - | Failed to | Payment gateway
margin 0.10 -> threshold 0.443 -> 2 of 5 new templates flagged: HikariPool-<*> - | Payment gateway
margin 0.20 -> threshold 0.543 -> 1 of 5 new templates flagged: HikariPool-<*> -
## Ranking is more trustworthy than the cut-off
the three real new templates score 0.678, 0.434, 0.459
the harmless reword scores 0.394, so it ranks below all three
a threshold between 0.394 and 0.434 would split them, but it is chosen after seeing the answer
+22
View File
@@ -0,0 +1,22 @@
# From findings to one incident and one summary
5 findings -> 1 incident(s)
window 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30, 5 findings, 542 events
## Summary without a model
ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x).
## The prompt a model would receive
You are helping an on-call engineer. Below are the anomalous log templates from one incident.
Write 3 sentences: what changed, the likely cause, and what to check first.
Only use facts from the list; do not invent hosts, versions or numbers.
Window: 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30
1. [ERROR] HikariPool: HikariPool-<*> - Connection is not available, request timed out after <*>ms. (NOVEL_TEMPLATE, 144 events, new template, distance 0.678 > 0.393)
2. [WARN] PaymentService: Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> (NOVEL_TEMPLATE, 90 events, new template, distance 0.459 > 0.393)
3. [ERROR] OrderController: Failed to process order <*>: Unable to acquire JDBC Connection (NOVEL_TEMPLATE, 108 events, new template, distance 0.434 > 0.393)
4. [INFO] OrderController: Order <*> placed by customer c-<*> total=<*> currency=INR (NOVEL_TEMPLATE, 156 events, new template, distance 0.394 > 0.393)
5. [WARN] PaymentService: Payment declined for order <*>: insufficient funds (RATE_SPIKE, 44 events, peak 44 per 5 min vs baseline mean 2.6 (std 0.9), z = 45.6)
## Size
raw target window: 2196 physical lines, 310589 characters
prompt: 1112 characters (0.4% of the raw window)
+6
View File
@@ -0,0 +1,6 @@
# The embedder is a seam: a remote one behind a stub /v1/embeddings
embedder: openai-compatible:stub-model, dimensions: 32
HTTP requests while fitting 10 baseline templates: 2
first request body: {"model":"stub-model","input":["INFO CatalogController GET /api/products/<*> <*> in <*> ms","INFO AuthFilter Token validated for user u-<*>","INFO Ord...
distance of the pool-timeout template through the stub: 0.520
The stub returns the hashing embedder's own vectors, so this shows the plumbing and says nothing about any real model.
@@ -0,0 +1,3 @@
# A model that returns a different vector length
configured dimensions: 32, stub returned 3
error: expected 32 dimensions but the model returned 3
+6
View File
@@ -0,0 +1,6 @@
# What the summariser sends to a chat endpoint (stub server)
request model: stub-model, temperature: 0, messages: 1
request content characters: 1112
contains a stack-trace line: false
reply: STUB REPLY: the pool ran out of connections.
Not run against a real model. The stub proves the request shape and the reply parsing.
+10
View File
@@ -0,0 +1,10 @@
# GET /api/incidents on a running Spring Boot application
HTTP 200
baselineLines=3947 targetLines=2196 baselineTemplates=10 targetTemplates=14 clusters=4 threshold=0.393
incidents: 1
NOVEL_TEMPLATE ERROR x144 HikariPool-<*> - Connection is not available, request timed out after <*>ms.
NOVEL_TEMPLATE WARN x90 Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>
NOVEL_TEMPLATE ERROR x108 Failed to process order <*>: Unable to acquire JDBC Connection
NOVEL_TEMPLATE INFO x156 Order <*> placed by customer c-<*> total=<*> currency=INR
RATE_SPIKE WARN x44 Payment declined for order <*>: insufficient funds
summary: ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x).
@@ -0,0 +1,15 @@
# A log file written by Spring Boot 4.2.0 itself (spring.application.name=shop)
## The first three lines, and the ERROR with its first stack-trace lines
2026-12-01T23:53:34.953+05:30 INFO 12412 --- [shop] [main] o.a.maven.surefire.booter.ForkedBooter : Starting ForkedBooter v3.5.4 using Java 25.0.5.1 with PID 12412 (started by root in /tmp/work/java-ai-agents/log-anomaly)
2026-12-01T23:53:34.975+05:30 INFO 12412 --- [shop] [main] o.a.maven.surefire.booter.ForkedBooter : No active profile set, falling back to 1 default profile: "default"
2026-12-01T23:53:37.369+05:30 INFO 12412 --- [shop] [main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 0 (http)
2026-12-01T23:53:38.561+05:30 ERROR 12412 --- [shop] [main] com.ankurm.shop.OrderController : Failed to process order 42
java.lang.IllegalStateException: quantity must be greater than 0
at com.ankurm.logs.RealSpringBootLogTest.theParserReadsWhatSpringBootActuallyWrites(RealSpringBootLogTest.java:23) ~[test-classes/:na]
## Parsed
96 physical lines, 11 events, 0 orphan lines
ERROR event: logger=OrderController message=Failed to process order 42 continuation lines=85
exception line: java.lang.IllegalStateException: quantity must be greater than 0
+14
View File
@@ -0,0 +1,14 @@
# The packaged jar answering curl
$ java -jar target/log-anomaly.jar --server.port=18080 &
$ curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log"
{
"baselineLines": 3947,
"targetLines": 2196,
"baselineTemplates": 10,
"targetTemplates": 14,
"clusters": 4
}
ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x).
$ curl -s -o /dev/null -w "%{http_code}" "localhost:18080/api/incidents?baseline=missing.log&target=missing.log"
500
+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm.agents</groupId>
<artifactId>java-ai-agents</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>log-anomaly</artifactId>
<name>Log anomaly detection for Spring Boot: template mining, embeddings, clustering and an incident summary</name>
<properties>
<!-- Verified on Maven Central 2026-12-01. These override the parent's older value for this module only. -->
<spring-boot.version>4.2.0</spring-boot.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>log-anomaly</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution><goals><goal>repackage</goal></goals></execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+64
View File
@@ -0,0 +1,64 @@
// Run with: java QuickStart.java (JDK 21 or newer, no Maven, no libraries)
//
// The whole idea in one file: mask the changing parts of each log line to get a template, turn every template into
// a vector of hashed words, and measure how far a new template is from the closest "normal" one.
import java.util.*;
import java.util.regex.Pattern;
public class QuickStart {
static final Pattern NUMBER = Pattern.compile("(?<![A-Za-z])\\d+(?:\\.\\d+)?|(?<=[A-Za-z])\\d+");
/** Step 1: Order 42 placed and Order 77 placed are the same template. */
static String template(String message) {
return NUMBER.matcher(message).replaceAll("<*>");
}
/** Step 2: a template becomes a unit-length vector by hashing its words into 64 buckets. */
static double[] embed(String text) {
double[] v = new double[64];
for (String w : text.toLowerCase().split("[^a-z]+")) {
if (w.length() > 1) {
int h = w.hashCode();
v[Math.floorMod(h, 64)] += (h >>> 31) == 0 ? 1 : -1;
}
}
double norm = Math.sqrt(Arrays.stream(v).map(x -> x * x).sum());
for (int i = 0; i < v.length; i++) v[i] /= norm;
return v;
}
/** Step 3: distance = 1 - cosine similarity. 0 means the same words, 1 means no words in common. */
static double distance(double[] a, double[] b) {
double dot = 0;
for (int i = 0; i < a.length; i++) dot += a[i] * b[i];
return 1 - dot;
}
public static void main(String[] args) {
List<String> normal = List.of(
"Order 42 placed by customer c-17", "Order 43 placed by customer c-90",
"Payment approved for order 42 in 80 ms", "Payment approved for order 43 in 95 ms",
"Reserved 2 units of SKU-1001", "Token validated for user u-1001");
List<String> today = List.of(
"Order 51 placed by customer c-3",
"HikariPool-1 - Connection is not available, request timed out after 30000ms.",
"Payment approved for order 52 in 90 ms but ledger write failed");
Set<String> known = new LinkedHashSet<>();
normal.forEach(m -> known.add(template(m)));
System.out.println("normal lines: " + normal.size() + ", normal templates: " + known.size());
known.forEach(t -> System.out.println(" " + t));
Map<String, double[]> vectors = new LinkedHashMap<>();
known.forEach(t -> vectors.put(t, embed(t)));
System.out.println();
for (String line : today) {
String t = template(line);
double nearest = vectors.values().stream().mapToDouble(v -> distance(embed(t), v)).min().orElseThrow();
String verdict = known.contains(t) ? "known template" : nearest > 0.5 ? "NEW and FAR from normal" : "new but close to normal";
System.out.printf("%.3f %-24s %s%n", nearest, verdict, t);
}
}
}
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Regenerates every file in output/: the tests write 01-12, the packaged jar plus curl writes 13.
# Timestamps, PIDs and timings in 12 and 13 differ on every run; the numbers in 01-11 do not.
set -eu
cd "$(dirname "$0")/.."
mvn -B -q -f ../pom.xml -pl log-anomaly package
java -cp target/classes com.ankurm.logs.SampleLogWriter target/sample-logs
{
echo "# The packaged jar answering curl"
echo '$ java -jar target/log-anomaly.jar --server.port=18080 &'
java -jar target/log-anomaly.jar --server.port=18080 --spring.main.banner-mode=off > target/jar.log 2>&1 &
PID=$!
trap 'kill $PID 2>/dev/null || true' EXIT
for i in $(seq 1 60); do curl -s -o /dev/null "localhost:18080/api/incidents" && break; sleep 1; done
echo '$ curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log"'
curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log" \
| python3 -c 'import json,sys; d=json.load(sys.stdin); print(json.dumps({k:d[k] for k in ("baselineLines","targetLines","baselineTemplates","targetTemplates","clusters")}, indent=2)); print(d["summaries"][0])'
echo
echo '$ curl -s -o /dev/null -w "%{http_code}" "localhost:18080/api/incidents?baseline=missing.log&target=missing.log"'
curl -s -o /dev/null -w "%{http_code}\n" "localhost:18080/api/incidents?baseline=missing.log&target=missing.log"
} > output/13-jar-curl.txt
echo "wrote output/13-jar-curl.txt"
@@ -0,0 +1,47 @@
package com.ankurm.logs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/** Reads a baseline log and a target log, fits the model on the first and reports incidents in the second. */
@Service
public class AnalysisService {
/** What one analysis found, plus the numbers that explain how much work was avoided. */
public record Report(int baselineLines, int targetLines, int baselineTemplates, int targetTemplates,
int clusters, double threshold, List<Incident> incidents, List<String> summaries) { }
private final Embedder embedder = new HashingEmbedder(256);
private final IncidentSummarizer summarizer = new TemplateSummarizer();
private final int k;
private final double margin;
public AnalysisService(@Value("${logs.clusters:4}") int k, @Value("${logs.margin:0.05}") double margin) {
this.k = k;
this.margin = margin;
}
public Report analyse(Path baselineLog, Path targetLog) throws IOException {
LogParser parser = new LogParser();
LogParser.Result base;
LogParser.Result target;
try (Stream<String> a = Files.lines(baselineLog); Stream<String> b = Files.lines(targetLog)) {
base = parser.parse(a);
target = parser.parse(b);
}
TemplateMiner miner = new TemplateMiner(false, 0);
BaselineModel model = new BaselineModel(embedder, miner.mine(base.events()), k);
double threshold = model.worstBaselineDistance() + margin;
AnomalyDetector detector = new AnomalyDetector(model, miner, base.events(), threshold, Duration.ofMinutes(5), 4.0, 15);
List<Incident> incidents = new IncidentBuilder(Duration.ofMinutes(10)).build(detector.detect(target.events()));
return new Report(base.physicalLines(), target.physicalLines(), model.templates().size(), miner.mine(target.events()).size(),
model.k(), threshold, incidents, incidents.stream().map(summarizer::summarise).toList());
}
}
@@ -0,0 +1,24 @@
package com.ankurm.logs;
import java.io.IOException;
import java.nio.file.Path;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** {@code GET /api/incidents?baseline=...&target=...} with paths on the server's own disk. Demo only: see the post. */
@RestController
public class AnomalyController {
private final AnalysisService service;
public AnomalyController(AnalysisService service) {
this.service = service;
}
@GetMapping("/api/incidents")
public AnalysisService.Report incidents(@RequestParam String baseline, @RequestParam String target) throws IOException {
return service.analyse(Path.of(baseline), Path.of(target));
}
}
@@ -0,0 +1,145 @@
package com.ankurm.logs;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ankurm.logs.TemplateMiner.Template;
/**
* Two independent detectors over a target window, because each one is blind to what the other sees:
* <ul>
* <li><b>Novel template</b> &mdash; the template never occurred in the baseline <em>and</em> its embedding is
* farther than {@code distanceThreshold} from every baseline cluster. Finds new kinds of messages.</li>
* <li><b>Rate spike</b> &mdash; the template did occur in the baseline, but its count per bucket is more than
* {@code sigma} standard deviations above the baseline mean. Finds known messages arriving too often.</li>
* </ul>
*/
public final class AnomalyDetector {
private final BaselineModel baseline;
private final TemplateMiner miner;
private final double distanceThreshold;
private final Duration bucket;
private final double sigma;
private final int minCount;
private final Map<String, double[]> baselineRate; // template key -> {mean, std} per bucket
public AnomalyDetector(BaselineModel baseline, TemplateMiner miner, List<LogEvent> baselineEvents,
double distanceThreshold, Duration bucket, double sigma, int minCount) {
this.baseline = baseline;
this.miner = miner;
this.distanceThreshold = distanceThreshold;
this.bucket = bucket;
this.sigma = sigma;
this.minCount = minCount;
this.baselineRate = rates(baselineEvents);
}
public double distanceThreshold() { return distanceThreshold; }
/** Per template: mean and standard deviation of the per-bucket count, over every bucket in the window. */
private Map<String, double[]> rates(List<LogEvent> events) {
Instant start = events.getFirst().timestamp();
Instant end = events.getLast().timestamp();
int buckets = (int) Math.max(1, Duration.between(start, end).dividedBy(bucket) + 1);
Map<String, int[]> perBucket = new HashMap<>();
for (LogEvent e : events) {
int b = (int) Duration.between(start, e.timestamp()).dividedBy(bucket);
perBucket.computeIfAbsent(keyOf(e), k -> new int[buckets])[b]++;
}
Map<String, double[]> out = new HashMap<>();
perBucket.forEach((k, counts) -> {
double mean = 0;
for (int c : counts) mean += c;
mean /= buckets;
double var = 0;
for (int c : counts) var += (c - mean) * (c - mean);
out.put(k, new double[]{mean, Math.sqrt(var / buckets)});
});
return out;
}
private String keyOf(LogEvent e) {
return miner.keyOf(e);
}
/** Runs both detectors over the target events. Findings come back highest score first. */
public List<Finding> detect(List<LogEvent> target) {
List<Finding> out = new ArrayList<>(novel(target));
out.addAll(spikes(target));
out.sort(Finding.BY_PRIORITY);
return out;
}
public List<Finding> novel(List<LogEvent> target) {
List<Finding> out = new ArrayList<>();
for (Template t : miner.mine(target)) {
if (baseline.knows(t)) {
continue;
}
double d = baseline.distance(t);
if (d > distanceThreshold) {
Instant[] span = span(target, t);
out.add(new Finding(Finding.Kind.NOVEL_TEMPLATE, t, d, t.count(), span[0], span[1],
"new template, distance %.3f > %.3f".formatted(d, distanceThreshold)));
}
}
return out;
}
public List<Finding> spikes(List<LogEvent> target) {
Instant start = target.getFirst().timestamp();
Map<String, int[]> perBucket = new HashMap<>();
int buckets = (int) Math.max(1, Duration.between(start, target.getLast().timestamp()).dividedBy(bucket) + 1);
for (LogEvent e : target) {
int b = (int) Duration.between(start, e.timestamp()).dividedBy(bucket);
perBucket.computeIfAbsent(keyOf(e), k -> new int[buckets])[b]++;
}
Map<String, Template> byKey = new HashMap<>();
for (Template t : miner.mine(target)) {
byKey.put(t.key(), t);
}
List<Finding> out = new ArrayList<>();
perBucket.forEach((key, counts) -> {
double[] base = baselineRate.get(key);
if (base == null) {
return; // not in the baseline: the novel-template detector owns it
}
double floor = Math.max(base[1], 0.5); // a template that never varied must not give a std of 0
int peak = 0;
int peakBucket = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] > peak) {
peak = counts[i];
peakBucket = i;
}
}
double z = (peak - base[0]) / floor;
if (peak >= minCount && z > sigma) {
Template t = byKey.get(key);
Instant bucketStart = start.plus(bucket.multipliedBy(peakBucket));
out.add(new Finding(Finding.Kind.RATE_SPIKE, t, z, peak, bucketStart, bucketStart.plus(bucket),
"peak %d per %d min vs baseline mean %.1f (std %.1f), z = %.1f"
.formatted(peak, bucket.toMinutes(), base[0], base[1], z)));
}
});
return out;
}
private Instant[] span(List<LogEvent> events, Template t) {
Instant first = null;
Instant last = null;
for (LogEvent e : events) {
if (keyOf(e).equals(t.key())) {
if (first == null) first = e.timestamp();
last = e.timestamp();
}
}
return new Instant[]{first, last};
}
}
@@ -0,0 +1,60 @@
package com.ankurm.logs;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ankurm.logs.TemplateMiner.Template;
/**
* What "normal" looks like: the templates seen in a baseline window, embedded and grouped into {@code k} clusters.
* A new template's <em>distance</em> is {@code 1 - cosine} to its nearest cluster centre: 0 means it reads like
* something normal, values near 1 mean it shares almost no words with anything normal.
*/
public final class BaselineModel {
private final Embedder embedder;
private final KMeans.Model clusters;
private final List<Template> templates;
private final Map<String, Integer> clusterOf = new HashMap<>();
public BaselineModel(Embedder embedder, List<Template> baselineTemplates, int k) {
this.embedder = embedder;
this.templates = baselineTemplates;
List<float[]> vectors = embedder.embedAll(baselineTemplates.stream().map(Template::embeddingText).toList());
this.clusters = KMeans.fit(vectors, k, 50);
for (int i = 0; i < baselineTemplates.size(); i++) {
clusterOf.put(baselineTemplates.get(i).key(), clusters.assignment()[i]);
}
}
public int k() { return clusters.k(); }
public List<Template> templates() { return templates; }
public boolean knows(Template t) { return clusterOf.containsKey(t.key()); }
public int clusterOf(Template t) { return clusterOf.getOrDefault(t.key(), -1); }
/** 1 - cosine similarity to the nearest cluster centre. */
public double distance(Template t) {
float[] v = embedder.embed(t.embeddingText());
int c = KMeans.nearest(v, clusters.centroids());
return Math.max(0.0, 1.0 - KMeans.dot(v, clusters.centroids()[c]));
}
public int nearestCluster(Template t) {
return KMeans.nearest(embedder.embed(t.embeddingText()), clusters.centroids());
}
/** The largest distance any baseline template has to its own cluster: the "worst-fitting normal". */
public double worstBaselineDistance() {
double worst = 0;
for (Template t : templates) {
worst = Math.max(worst, distance(t));
}
return worst;
}
public Embedder embedder() { return embedder; }
}
@@ -0,0 +1,21 @@
package com.ankurm.logs;
import java.util.List;
/**
* Turns text into a fixed-length vector. The detector needs two promises: the same text always gives the same
* vector, and similar text gives vectors that point the same way, so cosine similarity can compare them.
*/
public interface Embedder {
int dimensions();
/** Embeds one text. The result is L2-normalised, so a dot product is the cosine similarity. */
float[] embed(String text);
default List<float[]> embedAll(List<String> texts) {
return texts.stream().map(this::embed).toList();
}
String name();
}
@@ -0,0 +1,19 @@
package com.ankurm.logs;
import java.time.Instant;
import com.ankurm.logs.TemplateMiner.Template;
/** One reason to look at the logs: a template that is new and far from normal, or a known one that surged. */
public record Finding(Kind kind, Template template, double score, int count, Instant firstSeen, Instant lastSeen, String reason) {
public enum Kind { NOVEL_TEMPLATE, RATE_SPIKE }
/**
* Orders findings for a human: new kinds of message first, then surges, and inside each kind the higher score
* first. The two scores are different units (a cosine distance below 1, a z-score that can be 45), so they are
* never compared with each other.
*/
public static final java.util.Comparator<Finding> BY_PRIORITY =
java.util.Comparator.comparing(Finding::kind).thenComparing(java.util.Comparator.comparingDouble(Finding::score).reversed());
}
@@ -0,0 +1,83 @@
package com.ankurm.logs;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
* A bag-of-words embedder with no model and no network: split into words, hash each word and each neighbouring
* pair into one of {@code dimensions} buckets with a sign, then normalise (the "hashing trick").
*
* <p>It compares <em>words</em>, not <em>meaning</em>. That is enough to show every mechanism in this module
* offline, and it is also the reason the blind spots in the post exist. Swap in {@link OpenAiCompatibleEmbedder}
* for a real model; nothing else in the module changes.
*/
public final class HashingEmbedder implements Embedder {
private static final Set<String> STOP = Set.of("a", "an", "the", "of", "to", "and", "or", "for", "in", "on", "is",
"it", "this", "that", "with", "by", "be", "as", "at", "from");
private final int dimensions;
public HashingEmbedder(int dimensions) {
this.dimensions = dimensions;
}
@Override public int dimensions() { return dimensions; }
@Override public String name() { return "hashing-" + dimensions; }
@Override
public float[] embed(String text) {
List<String> words = words(text);
float[] v = new float[dimensions];
for (int i = 0; i < words.size(); i++) {
add(v, words.get(i), 1f);
if (i + 1 < words.size()) {
add(v, words.get(i) + " " + words.get(i + 1), 0.5f);
}
}
return normalise(v);
}
static float[] normalise(float[] v) {
double norm = 0;
for (float x : v) {
norm += x * x;
}
norm = Math.sqrt(norm);
if (norm > 0) {
for (int i = 0; i < v.length; i++) {
v[i] /= (float) norm;
}
}
return v;
}
private void add(float[] v, String feature, float weight) {
int h = fnv1a(feature);
v[Math.floorMod(h, dimensions)] += ((h >>> 31) == 0 ? 1f : -1f) * weight;
}
/** {@code PaymentService} becomes {@code payment service}; the {@code <*>} wildcard is dropped. */
static List<String> words(String text) {
String spaced = text.replaceAll("([a-z0-9])([A-Z])", "$1 $2").replaceAll("([A-Z]+)([A-Z][a-z])", "$1 $2");
List<String> out = new ArrayList<>();
for (String raw : spaced.toLowerCase(Locale.ROOT).split("[^a-z]+")) {
if (raw.length() >= 2 && !STOP.contains(raw)) {
out.add(raw);
}
}
return out;
}
private static int fnv1a(String s) {
int h = 0x811c9dc5;
for (int i = 0; i < s.length(); i++) {
h ^= s.charAt(i);
h *= 16777619;
}
return h;
}
}
@@ -0,0 +1,13 @@
package com.ankurm.logs;
import java.time.Instant;
import java.util.List;
/** Findings that overlap in time, treated as one thing that went wrong. */
public record Incident(Instant start, Instant end, List<Finding> findings, int affectedEvents) {
public String severity() {
boolean error = findings.stream().anyMatch(f -> f.template().level().equals("ERROR"));
return error ? "ERROR" : "WARN";
}
}
@@ -0,0 +1,50 @@
package com.ankurm.logs;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Groups findings into incidents: two findings belong together when their time spans are within {@code gap}
* of each other. Ten findings in ten minutes become one page, not ten.
*/
public final class IncidentBuilder {
private final Duration gap;
public IncidentBuilder(Duration gap) {
this.gap = gap;
}
public List<Incident> build(List<Finding> findings) {
List<Finding> sorted = new ArrayList<>(findings);
sorted.sort(Comparator.comparing(Finding::firstSeen));
List<Incident> out = new ArrayList<>();
List<Finding> group = new ArrayList<>();
Instant end = null;
for (Finding f : sorted) {
if (!group.isEmpty() && f.firstSeen().isAfter(end.plus(gap))) {
out.add(close(group));
group = new ArrayList<>();
end = null;
}
group.add(f);
end = end == null || f.lastSeen().isAfter(end) ? f.lastSeen() : end;
}
if (!group.isEmpty()) {
out.add(close(group));
}
return out;
}
private Incident close(List<Finding> group) {
Instant start = group.stream().map(Finding::firstSeen).min(Comparator.naturalOrder()).orElseThrow();
Instant end = group.stream().map(Finding::lastSeen).max(Comparator.naturalOrder()).orElseThrow();
int events = group.stream().mapToInt(Finding::count).sum();
List<Finding> byScore = new ArrayList<>(group);
byScore.sort(Finding.BY_PRIORITY);
return new Incident(start, end, byScore, events);
}
}
@@ -0,0 +1,30 @@
package com.ankurm.logs;
/** Turns an incident into a few sentences for a human on call. */
public interface IncidentSummarizer {
String summarise(Incident incident);
/** Log times are shown the way the log wrote them, in the application's own offset, not in UTC. */
static String at(java.time.Instant t) {
return java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(t.atOffset(java.time.ZoneOffset.ofHoursMinutes(5, 30))) + " +05:30";
}
/** The text a model would be sent, so its size can be measured without calling one. */
default String promptFor(Incident incident) {
StringBuilder b = new StringBuilder("""
You are helping an on-call engineer. Below are the anomalous log templates from one incident.
Write 3 sentences: what changed, the likely cause, and what to check first.
Only use facts from the list; do not invent hosts, versions or numbers.
""");
b.append("Window: ").append(at(incident.start())).append(" to ").append(at(incident.end())).append('\n');
int i = 1;
for (Finding f : incident.findings()) {
b.append(i++).append(". [").append(f.template().level()).append("] ").append(f.template().logger())
.append(": ").append(f.template().text()).append(" (").append(f.kind()).append(", ")
.append(f.count()).append(" events, ").append(f.reason()).append(")\n");
}
return b.toString();
}
}
@@ -0,0 +1,89 @@
package com.ankurm.logs;
import java.util.Arrays;
import java.util.List;
/**
* Spherical k-means: vectors and centroids are unit length and "closest" means the highest cosine similarity.
* Initialisation is farthest-first starting from the first vector, so the same input always gives the same
* clusters; there is no random seed to remember.
*/
public final class KMeans {
/** The fitted centroids and which cluster each input vector landed in. */
public record Model(float[][] centroids, int[] assignment) {
public int k() { return centroids.length; }
}
private KMeans() { }
public static Model fit(List<float[]> vectors, int k, int maxIterations) {
int n = vectors.size();
k = Math.min(k, n);
float[][] c = new float[k][];
c[0] = vectors.getFirst().clone();
for (int i = 1; i < k; i++) {
int far = 0;
double worst = 2;
for (int j = 0; j < n; j++) {
double best = -2;
for (int q = 0; q < i; q++) {
best = Math.max(best, dot(vectors.get(j), c[q]));
}
if (best < worst) {
worst = best;
far = j;
}
}
c[i] = vectors.get(far).clone();
}
int[] assign = new int[n];
Arrays.fill(assign, -1);
for (int iter = 0; iter < maxIterations; iter++) {
boolean changed = false;
for (int j = 0; j < n; j++) {
int nearest = nearest(vectors.get(j), c);
if (nearest != assign[j]) {
assign[j] = nearest;
changed = true;
}
}
if (!changed) {
break;
}
int dim = vectors.getFirst().length;
float[][] sum = new float[k][dim];
for (int j = 0; j < n; j++) {
float[] v = vectors.get(j);
for (int d = 0; d < dim; d++) {
sum[assign[j]][d] += v[d];
}
}
for (int i = 0; i < k; i++) {
c[i] = HashingEmbedder.normalise(sum[i]);
}
}
return new Model(c, assign);
}
public static int nearest(float[] v, float[][] centroids) {
int best = 0;
double bestSim = -2;
for (int i = 0; i < centroids.length; i++) {
double s = dot(v, centroids[i]);
if (s > bestSim) {
bestSim = s;
best = i;
}
}
return best;
}
public static double dot(float[] a, float[] b) {
double s = 0;
for (int i = 0; i < a.length; i++) {
s += a[i] * b[i];
}
return s;
}
}
@@ -0,0 +1,56 @@
package com.ankurm.logs;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import tools.jackson.databind.json.JsonMapper;
/**
* Sends {@link #promptFor} to any {@code POST /v1/chat/completions} endpoint and returns the reply text.
* The prompt holds the incident's anomalous <em>templates</em>, never the raw lines, which is what keeps it small.
* The tests run it against a stub server; it has not been run against a real model.
*/
public final class LlmSummarizer implements IncidentSummarizer {
private static final JsonMapper JSON = JsonMapper.builder().build();
private final URI endpoint;
private final String model;
private final String apiKey;
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
public LlmSummarizer(String baseUrl, String model, String apiKey) {
this.endpoint = URI.create(baseUrl.replaceAll("/+$", "") + "/chat/completions");
this.model = model;
this.apiKey = apiKey;
}
@Override
public String summarise(Incident incident) {
try {
String body = JSON.writeValueAsString(Map.of("model", model, "temperature", 0,
"messages", List.of(Map.of("role", "user", "content", promptFor(incident)))));
HttpRequest.Builder req = HttpRequest.newBuilder(endpoint).timeout(Duration.ofSeconds(60))
.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body));
if (apiKey != null && !apiKey.isBlank()) {
req.header("Authorization", "Bearer " + apiKey);
}
HttpResponse<String> res = http.send(req.build(), HttpResponse.BodyHandlers.ofString());
if (res.statusCode() / 100 != 2) {
throw new IllegalStateException("chat endpoint answered HTTP " + res.statusCode());
}
return JSON.readTree(res.body()).get("choices").get(0).get("message").get("content").asString();
} catch (IOException e) {
throw new IllegalStateException("chat request failed", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
}
}
@@ -0,0 +1,11 @@
package com.ankurm.logs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LogAnomalyApplication {
public static void main(String[] args) {
SpringApplication.run(LogAnomalyApplication.class, args);
}
}
@@ -0,0 +1,26 @@
package com.ankurm.logs;
import java.time.Instant;
import java.util.List;
/**
* One logical log event. A Java stack trace is many physical lines but one event, so the lines that follow the
* header line are kept in {@code continuation} instead of being parsed as events of their own.
*/
public record LogEvent(Instant timestamp, String level, String thread, String logger, String message,
List<String> continuation) {
/** The class name without its package, e.g. {@code c.a.shop.PaymentService} becomes {@code PaymentService}. */
public String shortLogger() {
int dot = logger.lastIndexOf('.');
return dot < 0 ? logger : logger.substring(dot + 1);
}
/**
* The line that names the exception, or an empty string when there is none. Spring Boot 4.2 writes an empty
* line between the message and the stack trace, so this skips blank lines instead of taking the first one.
*/
public String exceptionLine() {
return continuation.stream().map(String::strip).filter(l -> !l.isEmpty()).findFirst().orElse("");
}
}
@@ -0,0 +1,58 @@
package com.ankurm.logs;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Parses the default Spring Boot console/file layout:
* <pre>2026-11-30T09:00:00.123+05:30 INFO 4121 --- [shop] [nio-8080-exec-1] c.a.shop.OrderController : Order 42 placed</pre>
* The bracketed application name appears only when {@code spring.application.name} is set (observed on 4.2.0, see
* output/12); the pattern accepts logs with and without it.
* Any line that does not start with a timestamp is a continuation (a stack trace line) of the event before it.
*/
public final class LogParser {
private static final Pattern HEADER = Pattern.compile(
"^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}(?:Z|[+-]\\d{2}:\\d{2}))\\s+([A-Z]+)\\s+\\d+\\s+---\\s+"
+ "(?:\\[[^\\]]*]\\s+)?\\[([^\\]]*)]\\s+(\\S+)\\s+:\\s(.*)$");
/** What a parse found, including the lines it could not place. */
public record Result(List<LogEvent> events, int physicalLines, int orphanLines) { }
public Result parse(Stream<String> lines) {
List<LogEvent> events = new ArrayList<>();
List<String> cont = new ArrayList<>();
Header current = null;
int physical = 0;
int orphans = 0;
for (String line : (Iterable<String>) lines::iterator) {
physical++;
Matcher m = HEADER.matcher(line);
if (m.matches()) {
if (current != null) {
events.add(current.toEvent(cont));
}
current = new Header(OffsetDateTime.parse(m.group(1)).toInstant(), m.group(2), m.group(3), m.group(4), m.group(5));
cont = new ArrayList<>();
} else if (current != null) {
cont.add(line);
} else {
orphans++;
}
}
if (current != null) {
events.add(current.toEvent(cont));
}
return new Result(events, physical, orphans);
}
private record Header(java.time.Instant ts, String level, String thread, String logger, String message) {
LogEvent toEvent(List<String> cont) {
return new LogEvent(ts, level, thread, logger, message, List.copyOf(cont));
}
}
}
@@ -0,0 +1,88 @@
package com.ankurm.logs;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* Calls any {@code POST /v1/embeddings} endpoint that speaks the OpenAI request shape: OpenAI, Ollama
* ({@code http://localhost:11434/v1}), vLLM, LM Studio. The tests run it against a stub server, which proves the
* request and response handling and nothing about the quality of any real model's vectors.
*/
public final class OpenAiCompatibleEmbedder implements Embedder {
private static final JsonMapper JSON = JsonMapper.builder().build();
private final URI endpoint;
private final String model;
private final String apiKey;
private final int dimensions;
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
public OpenAiCompatibleEmbedder(String baseUrl, String model, String apiKey, int dimensions) {
this.endpoint = URI.create(baseUrl.replaceAll("/+$", "") + "/embeddings");
this.model = model;
this.apiKey = apiKey;
this.dimensions = dimensions;
}
@Override public int dimensions() { return dimensions; }
@Override public String name() { return "openai-compatible:" + model; }
@Override public float[] embed(String text) { return embedAll(List.of(text)).getFirst(); }
@Override
public List<float[]> embedAll(List<String> texts) {
List<float[]> out = new ArrayList<>();
for (int from = 0; from < texts.size(); from += 64) {
out.addAll(request(texts.subList(from, Math.min(from + 64, texts.size()))));
}
return out;
}
private List<float[]> request(List<String> batch) {
try {
String body = JSON.writeValueAsString(Map.of("model", model, "input", batch));
HttpRequest.Builder req = HttpRequest.newBuilder(endpoint).timeout(Duration.ofSeconds(60))
.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body));
if (apiKey != null && !apiKey.isBlank()) {
req.header("Authorization", "Bearer " + apiKey);
}
HttpResponse<String> res = http.send(req.build(), HttpResponse.BodyHandlers.ofString());
if (res.statusCode() / 100 != 2) {
throw new IllegalStateException("embeddings endpoint answered HTTP " + res.statusCode() + ": " + res.body());
}
List<float[]> out = new ArrayList<>();
for (JsonNode item : JSON.readTree(res.body()).get("data")) {
JsonNode arr = item.get("embedding");
if (arr.size() != dimensions) {
throw new IllegalStateException("expected " + dimensions + " dimensions but the model returned " + arr.size());
}
float[] v = new float[dimensions];
for (int i = 0; i < dimensions; i++) {
v[i] = (float) arr.get(i).asDouble();
}
out.add(HashingEmbedder.normalise(v));
}
if (out.size() != batch.size()) {
throw new IllegalStateException("sent " + batch.size() + " texts but got " + out.size() + " vectors back");
}
return out;
} catch (IOException e) {
throw new IllegalStateException("embeddings request failed", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
}
}
@@ -0,0 +1,18 @@
package com.ankurm.logs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** {@code java -cp target/classes com.ankurm.logs.SampleLogWriter <dir>} writes baseline.log and target.log for trying the endpoint. */
public final class SampleLogWriter {
public static void main(String[] args) throws IOException {
Path dir = Path.of(args.length > 0 ? args[0] : "sample-logs");
Files.createDirectories(dir);
SyntheticLogs g = new SyntheticLogs(42, false);
Files.write(dir.resolve("baseline.log"), g.baseline(SyntheticLogs.BASELINE_START, 120));
Files.write(dir.resolve("target.log"), g.target(SyntheticLogs.BASELINE_START.plusSeconds(7200), 30, 12));
System.out.println("wrote " + dir.resolve("baseline.log") + " and " + dir.resolve("target.log"));
}
}
@@ -0,0 +1,157 @@
package com.ankurm.logs;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Writes Spring Boot formatted log lines for a pretend shop, from a seeded random generator, so every run of the
* tests sees the same bytes. <b>This is synthetic data</b>: it contains exactly the failure shapes the post needs
* (a new error, a surge of a known warning, a numbers-only change, a look-alike line, a harmless reword) and no
* others. Real logs are messier; the post says what that costs.
*/
public final class SyntheticLogs {
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx");
private static final ZoneOffset IST = ZoneOffset.ofHoursMinutes(5, 30);
private static final String[] NAMES = {"alice", "bob", "carol", "dave", "erin", "frank", "grace", "heidi", "ivan",
"judy", "mallory", "niaj", "olivia", "peggy", "rupert", "sybil", "trent", "victor", "wendy", "zoe"};
/** The pretend start of the baseline window: 2026-11-30 09:00 IST. */
public static final Instant BASELINE_START = OffsetDateTime.of(2026, 11, 30, 9, 0, 0, 0, IST).toInstant();
private final Random rnd;
private final boolean realNames;
private int pid = 4121;
public SyntheticLogs(long seed, boolean realNames) {
this.rnd = new Random(seed);
this.realNames = realNames;
}
/** Normal traffic only: about 30 lines a minute. */
public List<String> baseline(Instant start, int minutes) {
List<String> out = new ArrayList<>();
for (int m = 0; m < minutes; m++) {
minute(out, start.plusSeconds(60L * m), false, false, false);
}
return out;
}
/**
* A target window. After {@code incidentAtMinute} the connection pool starts timing out (new ERROR templates),
* payments get declined far more often (a known WARN surging), the pool statistics show exhaustion (same
* template, different numbers) and a payment line appears that looks almost like a normal one.
* From minute 5 the order line is reworded, as a deployment would do.
*/
public List<String> target(Instant start, int minutes, int incidentAtMinute) {
List<String> out = new ArrayList<>();
for (int m = 0; m < minutes; m++) {
minute(out, start.plusSeconds(60L * m), m >= 5, true, m >= incidentAtMinute);
}
return out;
}
private void minute(List<String> out, Instant t, boolean deployed, boolean target, boolean incident) {
List<String> lines = new ArrayList<>();
int base = 30;
for (int i = 0; i < base; i++) {
int id = 10_000 + rnd.nextInt(90_000);
int pick = rnd.nextInt(100);
long ms = 0;
if (pick < 20) {
lines.add(line(t, "INFO", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.OrderController",
deployed
? "Order %d placed by customer c-%d total=%d.%02d currency=INR".formatted(id, rnd.nextInt(5000), rnd.nextInt(9000), rnd.nextInt(100))
: "Order %d placed by customer c-%d total=%d.%02d".formatted(id, rnd.nextInt(5000), rnd.nextInt(9000), rnd.nextInt(100))));
} else if (pick < 38) {
lines.add(line(t, "INFO", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.PaymentService",
"Payment approved for order %d in %d ms".formatted(id, 40 + rnd.nextInt(160))));
} else if (pick < 58) {
lines.add(line(t, "INFO", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.InventoryService",
"Reserved %d units of SKU-%d".formatted(1 + rnd.nextInt(5), 1000 + rnd.nextInt(4000))));
} else if (pick < 80) {
lines.add(line(t, "INFO", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.CatalogController",
"GET /api/products/%d 200 in %d ms".formatted(rnd.nextInt(2000), 3 + rnd.nextInt(40))));
} else {
String who = realNames ? NAMES[rnd.nextInt(NAMES.length)] : "u-" + (1000 + rnd.nextInt(500));
lines.add(line(t, "INFO", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.AuthFilter",
"Token validated for user " + who));
}
}
// Rare lines that exist in normal traffic too, so "normal" is not only INFO.
if (rnd.nextInt(100) < 55) {
lines.add(line(t, "WARN", "nio-8080-exec-2", "c.a.shop.PaymentService",
"Payment declined for order %d: insufficient funds".formatted(10_000 + rnd.nextInt(90_000))));
}
if (rnd.nextInt(100) < 35) {
lines.add(line(t, "WARN", "nio-8080-exec-5", "c.a.shop.SlowQueryDetector",
"Slow query (%d ms): select * from orders where customer_id = ?".formatted(800 + rnd.nextInt(900))));
}
if (rnd.nextInt(100) < 25) {
lines.add(line(t, "ERROR", "nio-8080-exec-3", "c.a.shop.OrderController",
"Failed to process order %d: validation failed".formatted(10_000 + rnd.nextInt(90_000)),
"jakarta.validation.ConstraintViolationException: quantity must be greater than 0",
"\tat com.ankurm.shop.OrderController.place(OrderController.java:58)",
"\tat java.base/java.lang.reflect.Method.invoke(Method.java:580)"));
}
if (t.getEpochSecond() % 3600 < 60) {
lines.add(line(t, "INFO", "scheduling-1", "c.a.shop.CacheRefresher", "Nightly cache refresh completed in %d ms".formatted(900 + rnd.nextInt(300))));
}
// The pool logs its statistics every 30 seconds; here once a minute is enough.
int active = incident ? 10 : 1 + rnd.nextInt(3);
int waiting = incident ? 25 + rnd.nextInt(20) : 0;
lines.add(line(t, "INFO", "HikariPool-1 housekeeper", "com.zaxxer.hikari.pool.HikariPool",
"HikariPool-1 - Pool stats (total=10, active=%d, idle=%d, waiting=%d)".formatted(active, 10 - active, waiting)));
if (target && incident) {
for (int i = 0; i < 8; i++) {
lines.add(line(t, "ERROR", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "com.zaxxer.hikari.pool.HikariPool",
"HikariPool-1 - Connection is not available, request timed out after 30000ms.",
"java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.",
"\tat com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:686)",
"\tat com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:179)"));
}
for (int i = 0; i < 6; i++) {
lines.add(line(t, "ERROR", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.OrderController",
"Failed to process order %d: Unable to acquire JDBC Connection".formatted(10_000 + rnd.nextInt(90_000)),
"org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection",
"\tat org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:84)"));
}
for (int i = 0; i < 5; i++) {
lines.add(line(t, "WARN", "nio-8080-exec-" + (1 + rnd.nextInt(8)), "c.a.shop.PaymentService",
"Payment gateway timeout after %d ms for order %d, retry %d of 3".formatted(2000 + rnd.nextInt(3000), 10_000 + rnd.nextInt(90_000), 1 + rnd.nextInt(3))));
}
for (int i = 0; i < 8; i++) {
lines.add(line(t, "WARN", "nio-8080-exec-2", "c.a.shop.PaymentService",
"Payment declined for order %d: insufficient funds".formatted(10_000 + rnd.nextInt(90_000))));
}
for (int i = 0; i < 4; i++) {
lines.add(line(t, "INFO", "nio-8080-exec-4", "c.a.shop.PaymentService",
"Payment approved for order %d in %d ms but ledger write failed".formatted(10_000 + rnd.nextInt(90_000), 40 + rnd.nextInt(160))));
}
}
// spread the minute's lines over its 60 seconds, in order
for (int i = 0; i < lines.size(); i++) {
for (String physical : lines.get(i).replace("@@", stamp(t.plusMillis((long) (i * 59_000.0 / lines.size())))).split("\n")) {
out.add(physical); // a stack trace is several physical lines
}
}
}
private String stamp(Instant t) {
return TS.format(t.atOffset(IST));
}
private String line(Instant t, String level, String thread, String logger, String message, String... trace) {
StringBuilder b = new StringBuilder("@@ ").append("%5s %d --- [shop] [%15s] %-40s : %s".formatted(level, pid, thread, logger, message));
for (String s : trace) {
b.append('\n').append(s);
}
return b.toString();
}
}
@@ -0,0 +1,134 @@
package com.ankurm.logs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Turns thousands of log lines into a few dozen templates by replacing the parts that change (ids, numbers, IPs)
* with {@code <*>}. {@code Order 42 placed} and {@code Order 77 placed} are the same template.
*
* <p>Pass 1 masks anything that looks like an identifier or a number. Pass 2 (optional) handles words that vary
* but contain no digit, such as user names: inside a group of templates that share a logger, level, length and
* first two words, a position holding more than {@code maxDistinct} different words is also made a wildcard.
* This is a small cousin of the Drain parse tree, not a replacement for it.
*/
public final class TemplateMiner {
public static final String WILDCARD = "<*>";
private static final Pattern UUID = Pattern.compile("\\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");
private static final Pattern IPV4 = Pattern.compile("\\b\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?\\b");
private static final Pattern HEX = Pattern.compile("\\b0x[0-9a-fA-F]+\\b");
private static final Pattern NUMBER = Pattern.compile("(?<![A-Za-z])\\d+(?:\\.\\d+)?|(?<=[A-Za-z])\\d+");
/** One template and how often it was seen. */
public record Template(String level, String logger, String text, int count, String example) {
/** The string that is embedded: the level and class name carry meaning, so they travel with the text. */
public String embeddingText() {
return level + " " + logger + " " + text;
}
public String key() {
return level + "|" + logger + "|" + text;
}
}
private final boolean mergeVaryingWords;
private final int maxDistinct;
/** Learned by {@link #fit}: for each group, which word positions are wildcards. */
private final Map<String, boolean[]> wildcards = new HashMap<>();
public TemplateMiner(boolean mergeVaryingWords, int maxDistinct) {
this.mergeVaryingWords = mergeVaryingWords;
this.maxDistinct = maxDistinct;
}
/** Pass 1 only: digits and identifiers masked. */
public static String mask(String message) {
String s = UUID.matcher(message).replaceAll(WILDCARD);
s = IPV4.matcher(s).replaceAll(WILDCARD);
s = HEX.matcher(s).replaceAll(WILDCARD);
return NUMBER.matcher(s).replaceAll(WILDCARD);
}
private static String group(String level, String logger, String[] w) {
return level + "|" + logger + "|" + w.length + "|" + w[0] + " " + (w.length > 1 ? w[1] : "");
}
/** The template text of one event: pass 1, then the pass-2 wildcards learned by {@link #fit}. */
public String templateOf(LogEvent e) {
String masked = mask(e.message());
if (wildcards.isEmpty()) {
return masked;
}
String[] w = masked.split(" ");
boolean[] wild = wildcards.get(group(e.level(), e.shortLogger(), w));
if (wild == null) {
return masked;
}
for (int i = 0; i < w.length; i++) {
if (wild[i]) {
w[i] = WILDCARD;
}
}
return String.join(" ", w);
}
/** The key a detector uses to compare events: level, class, template. */
public String keyOf(LogEvent e) {
return e.level() + "|" + e.shortLogger() + "|" + templateOf(e);
}
/** Learns pass-2 wildcards from a baseline window. Does nothing when pass 2 is off. */
public void fit(List<LogEvent> baseline) {
wildcards.clear();
if (!mergeVaryingWords) {
return;
}
Map<String, List<String[]>> groups = new LinkedHashMap<>();
Set<String> seen = new HashSet<>();
for (LogEvent e : baseline) {
String masked = mask(e.message());
if (seen.add(e.level() + "|" + e.shortLogger() + "|" + masked)) {
String[] w = masked.split(" ");
groups.computeIfAbsent(group(e.level(), e.shortLogger(), w), k -> new ArrayList<>()).add(w);
}
}
groups.forEach((g, list) -> {
int len = list.getFirst().length;
boolean[] wild = new boolean[len];
boolean any = false;
for (int pos = 0; pos < len; pos++) {
final int p = pos;
wild[pos] = list.stream().map(w -> w[p]).distinct().count() > maxDistinct;
any |= wild[pos];
}
if (any) {
wildcards.put(g, wild);
}
});
}
/** Counts events per (level, logger, template), most frequent first. */
public List<Template> mine(List<LogEvent> events) {
Map<String, int[]> counts = new LinkedHashMap<>();
Map<String, LogEvent> examples = new HashMap<>();
for (LogEvent e : events) {
String key = keyOf(e);
counts.computeIfAbsent(key, k -> new int[1])[0]++;
examples.putIfAbsent(key, e);
}
List<Template> out = new ArrayList<>();
counts.forEach((k, c) -> {
String[] p = k.split("\\|", 3);
out.add(new Template(p[0], p[1], p[2], c[0], examples.get(k).message()));
});
out.sort((a, b) -> Integer.compare(b.count(), a.count()));
return out;
}
}
@@ -0,0 +1,18 @@
package com.ankurm.logs;
import java.util.stream.Collectors;
/** The no-model summary: counts, window and the top templates in plain sentences. It never invents anything. */
public final class TemplateSummarizer implements IncidentSummarizer {
@Override
public String summarise(Incident incident) {
long novel = incident.findings().stream().filter(f -> f.kind() == Finding.Kind.NOVEL_TEMPLATE).count();
long spikes = incident.findings().size() - novel;
String top = incident.findings().stream().limit(3)
.map(f -> "\"" + f.template().text() + "\" (" + f.template().logger() + ", " + f.count() + "x)")
.collect(Collectors.joining("; "));
return "%s incident from %s to %s: %d new message kinds and %d known messages surging, %d events in all. Top: %s."
.formatted(incident.severity(), IncidentSummarizer.at(incident.start()), IncidentSummarizer.at(incident.end()), novel, spikes, incident.affectedEvents(), top);
}
}
@@ -0,0 +1,53 @@
package com.ankurm.logs;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class EndpointTest {
@LocalServerPort int port;
@TempDir Path tmp;
@Test
void theEndpointReportsTheIncident() throws Exception {
Fixtures f = new Fixtures();
Path base = Files.write(tmp.resolve("baseline.log"), f.baselineLines);
Path target = Files.write(tmp.resolve("target.log"), f.targetLines);
String url = "http://localhost:%d/api/incidents?baseline=%s&target=%s".formatted(port,
URLEncoder.encode(base.toString(), StandardCharsets.UTF_8), URLEncoder.encode(target.toString(), StandardCharsets.UTF_8));
HttpResponse<String> res = HttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create(url)).GET().build(), HttpResponse.BodyHandlers.ofString());
JsonNode body = JsonMapper.builder().build().readTree(res.body());
Transcript t = new Transcript("11-endpoint.txt", "GET /api/incidents on a running Spring Boot application");
t.line("HTTP %d", res.statusCode());
t.line("baselineLines=%s targetLines=%s baselineTemplates=%s targetTemplates=%s clusters=%s threshold=%.3f",
body.get("baselineLines"), body.get("targetLines"), body.get("baselineTemplates"), body.get("targetTemplates"), body.get("clusters"), body.get("threshold").asDouble());
t.line("incidents: %d", body.get("incidents").size());
body.get("incidents").get(0).get("findings").forEach(x -> t.line(" %s %s x%s %s", x.get("kind").asString(), x.get("template").get("level").asString(), x.get("count"), x.get("template").get("text").asString()));
t.line("summary: %s", body.get("summaries").get(0).asString());
t.write();
assertThat(res.statusCode()).isEqualTo(200);
assertThat(body.get("incidents")).hasSize(1);
assertThat(body.get("incidents").get(0).get("findings")).hasSize(5);
assertThat(body.get("summaries").get(0).asString()).contains("ERROR incident");
}
}
@@ -0,0 +1,45 @@
package com.ankurm.logs;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import com.ankurm.logs.TemplateMiner.Template;
/** The same two windows for every test: 120 minutes of normal traffic, then 30 minutes with an incident from minute 12. */
final class Fixtures {
static final Instant TARGET_START = SyntheticLogs.BASELINE_START.plusSeconds(7200);
static final int K = 4;
static final double MARGIN = 0.05;
final List<String> baselineLines;
final List<String> targetLines;
final LogParser.Result baseline;
final LogParser.Result target;
final TemplateMiner miner = new TemplateMiner(false, 0);
final List<Template> baselineTemplates;
final List<Template> targetTemplates;
final Embedder embedder = new HashingEmbedder(256);
final BaselineModel model;
final double threshold;
final AnomalyDetector detector;
Fixtures() {
SyntheticLogs g = new SyntheticLogs(42, false);
baselineLines = g.baseline(SyntheticLogs.BASELINE_START, 120);
targetLines = g.target(TARGET_START, 30, 12);
LogParser p = new LogParser();
baseline = p.parse(baselineLines.stream());
target = p.parse(targetLines.stream());
baselineTemplates = miner.mine(baseline.events());
targetTemplates = miner.mine(target.events());
model = new BaselineModel(embedder, baselineTemplates, K);
threshold = model.worstBaselineDistance() + MARGIN;
detector = new AnomalyDetector(model, miner, baseline.events(), threshold, Duration.ofMinutes(5), 4.0, 15);
}
Template target(String startsWith) {
return targetTemplates.stream().filter(t -> t.text().startsWith(startsWith)).findFirst().orElseThrow();
}
}
@@ -0,0 +1,215 @@
package com.ankurm.logs;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import com.ankurm.logs.TemplateMiner.Template;
/** Every figure in the post is an assertion here and a line in output/. */
class LogAnomalyTest {
private final Fixtures f = new Fixtures();
@Test
void parsesSpringBootLinesAndFoldsStackTraces() throws IOException {
Transcript t = new Transcript("01-parse.txt", "Parsing Spring Boot log lines");
t.section("First lines of the baseline");
f.baselineLines.stream().limit(3).forEach(t::line);
t.section("An ERROR with a stack trace: one event, several physical lines");
int at = f.targetLines.indexOf(f.targetLines.stream().filter(l -> l.contains("Connection is not available")).findFirst().orElseThrow());
f.targetLines.subList(at, at + 4).forEach(t::line);
t.section("Counts");
t.line("baseline: %d physical lines, %d events, %d orphan lines", f.baseline.physicalLines(), f.baseline.events().size(), f.baseline.orphanLines());
t.line("target: %d physical lines, %d events, %d orphan lines", f.target.physicalLines(), f.target.events().size(), f.target.orphanLines());
LogEvent withTrace = f.target.events().stream().filter(e -> e.message().startsWith("HikariPool-1 - Connection")).findFirst().orElseThrow();
t.line("that ERROR event: level=%s logger=%s continuation lines=%d", withTrace.level(), withTrace.shortLogger(), withTrace.continuation().size());
t.line("exception line: %s", withTrace.exceptionLine());
t.section("The same line without the application name bracket");
String old = "2026-11-30T09:00:00.123+05:30 INFO 4121 --- [nio-8080-exec-1] c.a.shop.OrderController : Order 42 placed";
LogEvent e = new LogParser().parse(java.util.stream.Stream.of(old)).events().getFirst();
t.line("parsed: level=%s thread=%s logger=%s message=%s", e.level(), e.thread(), e.shortLogger(), e.message());
t.write();
assertThat(f.baseline.orphanLines()).isZero();
assertThat(f.target.physicalLines()).isGreaterThan(f.target.events().size());
assertThat(withTrace.continuation()).hasSize(3);
assertThat(e.message()).isEqualTo("Order 42 placed");
}
@Test
void miningCollapsesThousandsOfLinesIntoTenTemplates() throws IOException {
Transcript t = new Transcript("02-templates.txt", "Template mining");
t.section("Baseline: " + f.baseline.events().size() + " events become " + f.baselineTemplates.size() + " templates");
f.baselineTemplates.forEach(x -> t.line("%5d %-5s %-20s %s", x.count(), x.level(), x.logger(), x.text()));
t.section("Failure: words that are not numbers. Same traffic, real user names instead of u-1042");
SyntheticLogs named = new SyntheticLogs(42, true);
var events = new LogParser().parse(named.baseline(SyntheticLogs.BASELINE_START, 120).stream()).events();
TemplateMiner plain = new TemplateMiner(false, 0);
long authPlain = plain.mine(events).stream().filter(x -> x.logger().equals("AuthFilter")).count();
TemplateMiner merging = new TemplateMiner(true, 8);
merging.fit(events);
long authMerged = merging.mine(events).stream().filter(x -> x.logger().equals("AuthFilter")).count();
t.line("AuthFilter templates, digits-only masking: %d", authPlain);
t.line("AuthFilter templates, with the second pass: %d", authMerged);
t.line("all templates, digits-only masking: %d", plain.mine(events).size());
t.line("all templates, with the second pass: %d", merging.mine(events).size());
merging.mine(events).stream().filter(x -> x.logger().equals("AuthFilter")).forEach(x -> t.line(" %d %s", x.count(), x.text()));
t.write();
assertThat(f.baselineTemplates).hasSize(10);
assertThat(authPlain).isEqualTo(20);
assertThat(authMerged).isEqualTo(1);
}
@Test
void embeddingsCompareWordsNotMeaning() throws IOException {
Transcript t = new Transcript("03-embeddings.txt", "What a hashing embedder considers close (distance = 1 - cosine)");
String[][] pairs = {
{"WARN PaymentService Payment declined for order <*>: insufficient funds", "INFO PaymentService Payment approved for order <*> in <*> ms"},
{"ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection", "ERROR OrderController Failed to process order <*>: validation failed"},
{"ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection", "ERROR HikariPool Could not get a database connection from the pool"},
{"INFO PaymentService Payment approved for order <*> in <*> ms", "INFO PaymentService Payment approved for order <*> in <*> ms but ledger write failed"},
{"INFO AuthFilter Token validated for user u-<*>", "ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms."},
};
double[] d = new double[pairs.length];
for (int i = 0; i < pairs.length; i++) {
d[i] = 1 - KMeans.dot(f.embedder.embed(pairs[i][0]), f.embedder.embed(pairs[i][1]));
t.line("distance %.3f", d[i]).line(" A: %s", pairs[i][0]).line(" B: %s", pairs[i][1]).blank();
}
t.write();
assertThat(d[0]).as("approved vs declined share most words").isLessThan(0.45);
assertThat(d[2]).as("same meaning, different words").isGreaterThan(0.75);
assertThat(d[2]).isGreaterThan(d[1]);
assertThat(d[3]).isLessThan(0.30);
assertThat(d[4]).isGreaterThan(0.9);
}
@Test
void clusterCountDecidesWhatCountsAsNormal() throws IOException {
Transcript t = new Transcript("04-clusters.txt", "k decides how far from normal a template can be");
t.section("Baseline templates grouped with k = " + Fixtures.K);
int[] cluster = new int[f.baselineTemplates.size()];
for (int c = 0; c < f.model.k(); c++) {
final int cc = c;
t.line("cluster %d:", c);
f.baselineTemplates.stream().filter(x -> f.model.clusterOf(x) == cc)
.forEach(x -> t.line(" %-5s %-20s %s (distance to centre %.3f)", x.level(), x.logger(), x.text(), f.model.distance(x)));
}
List<Template> novel = List.of(f.target("HikariPool-<*> - Connection"), f.target("Failed to process order <*>: Unable"),
f.target("Payment gateway timeout"), f.target("Order <*> placed by customer c-<*> total=<*> currency"), f.target("Payment approved for order <*> in <*> ms but"));
t.section("Distance of the five new templates, and the threshold, for different k (threshold = worst baseline distance + 0.05)");
t.line("%-4s %-12s %-10s | %s", "k", "worst-normal", "threshold", "hikari jdbc gateway reword ledger-fail");
double[][] byK = new double[4][];
int row = 0;
for (int k : new int[]{1, 2, 4, f.baselineTemplates.size()}) {
BaselineModel m = new BaselineModel(f.embedder, f.baselineTemplates, k);
double worst = m.worstBaselineDistance();
double[] ds = novel.stream().mapToDouble(m::distance).toArray();
byK[row++] = new double[]{worst, ds[0], ds[1], ds[2], ds[3], ds[4]};
StringBuilder b = new StringBuilder();
for (double x : ds) {
b.append("%.3f%s ".formatted(x, x > worst + Fixtures.MARGIN ? "*" : " "));
}
t.line("%-4d %-12.3f %-10.3f | %s", k, worst, worst + Fixtures.MARGIN, b.toString().strip());
}
t.line("(* = flagged at that threshold)");
t.write();
assertThat(f.model.k()).isEqualTo(4);
assertThat(byK[3][0]).as("with k = number of templates every baseline template is its own centre").isLessThan(1e-6);
assertThat(byK[0][0]).as("k=1: one centre for everything makes 'normal' very wide").isGreaterThan(byK[2][0]);
}
@Test
void bothDetectorsRunAndTheirBlindSpotsAreReal() throws IOException {
List<Finding> findings = f.detector.detect(f.target.events());
Transcript t = new Transcript("05-detection.txt", "Findings for the 30-minute target window (incident starts at minute 12)");
t.line("threshold %.3f (worst baseline distance %.3f + margin %.2f), k = %d", f.threshold, f.model.worstBaselineDistance(), Fixtures.MARGIN, f.model.k());
t.section("Flagged");
findings.forEach(x -> t.line("%-14s %-5s %-24s %-72s x%d %s", x.kind(), x.template().level(), x.template().logger(), x.template().text(), x.count(), x.reason()));
t.section("Not flagged, although something is wrong");
Template pool = f.targetTemplates.stream().filter(x -> x.logger().equals("HikariPool") && x.text().contains("Pool stats")).findFirst().orElseThrow();
t.line("pool stats template known to the baseline: %s", f.model.knows(pool));
f.target.events().stream().filter(e -> e.message().contains("Pool stats")).skip(14).limit(1).forEach(e -> t.line(" during the incident: %s", e.message()));
f.baseline.events().stream().filter(e -> e.message().contains("Pool stats")).skip(30).limit(1).forEach(e -> t.line(" during normal times: %s", e.message()));
Template ledger = f.target("Payment approved for order <*> in <*> ms but");
t.line("'but ledger write failed' has distance %.3f, threshold %.3f, so it is %s", f.model.distance(ledger), f.threshold,
f.model.distance(ledger) > f.threshold ? "flagged" : "NOT flagged");
t.section("Flagged, although nothing is wrong");
Template reword = f.target("Order <*> placed by customer c-<*> total=<*> currency");
t.line("the deployment's reworded order line has distance %.3f against threshold %.3f", f.model.distance(reword), f.threshold);
t.write();
List<String> texts = findings.stream().map(x -> x.template().text()).toList();
assertThat(texts).anyMatch(s -> s.startsWith("HikariPool-<*> - Connection is not available"));
assertThat(texts).anyMatch(s -> s.startsWith("Failed to process order <*>: Unable to acquire"));
assertThat(texts).anyMatch(s -> s.startsWith("Payment gateway timeout"));
assertThat(findings).anyMatch(x -> x.kind() == Finding.Kind.RATE_SPIKE && x.template().text().startsWith("Payment declined"));
assertThat(f.model.knows(pool)).isTrue();
assertThat(texts).noneMatch(s -> s.contains("Pool stats"));
assertThat(f.model.distance(ledger)).isLessThan(f.threshold);
assertThat(f.model.distance(reword)).isGreaterThan(f.threshold);
}
@Test
void thresholdChoiceMovesTheFalsePositive() throws IOException {
Transcript t = new Transcript("06-threshold-sweep.txt", "What each margin flags, k = " + Fixtures.K);
double worst = f.model.worstBaselineDistance();
List<Template> novel = f.targetTemplates.stream().filter(x -> !f.model.knows(x)).toList();
t.line("worst baseline distance: %.3f", worst);
List<Integer> counts = new ArrayList<>();
for (double margin : new double[]{0.0, 0.05, 0.10, 0.20}) {
double th = worst + margin;
List<String> flagged = novel.stream().filter(x -> f.model.distance(x) > th).map(x -> x.text().split(" ")[0] + " " + x.text().split(" ")[1]).toList();
counts.add(flagged.size());
t.line("margin %.2f -> threshold %.3f -> %d of %d new templates flagged: %s", margin, th, flagged.size(), novel.size(), flagged.stream().collect(Collectors.joining(" | ")));
}
t.section("Ranking is more trustworthy than the cut-off");
double reword = f.model.distance(f.target("Order <*> placed by customer c-<*> total=<*> currency"));
List<Double> real = List.of(f.model.distance(f.target("HikariPool-<*> - Connection")), f.model.distance(f.target("Failed to process order <*>: Unable")),
f.model.distance(f.target("Payment gateway timeout")));
t.line("the three real new templates score %s", real.stream().map("%.3f"::formatted).collect(Collectors.joining(", ")));
t.line("the harmless reword scores %.3f, so it ranks below all three", reword);
t.line("a threshold between %.3f and %.3f would split them, but it is chosen after seeing the answer", reword, real.stream().min(Double::compare).orElseThrow());
t.write();
assertThat(real).allSatisfy(d -> assertThat(d).isGreaterThan(reword));
assertThat(novel).hasSize(5);
assertThat(counts.getFirst()).isGreaterThanOrEqualTo(counts.getLast());
}
@Test
void incidentsShrinkThePageAndThePrompt() throws IOException {
List<Finding> findings = f.detector.detect(f.target.events());
List<Incident> incidents = new IncidentBuilder(Duration.ofMinutes(10)).build(findings);
IncidentSummarizer s = new TemplateSummarizer();
Transcript t = new Transcript("07-incident.txt", "From findings to one incident and one summary");
t.line("%d findings -> %d incident(s)", findings.size(), incidents.size());
Incident inc = incidents.getFirst();
t.line("window %s to %s, %d findings, %d events", IncidentSummarizer.at(inc.start()), IncidentSummarizer.at(inc.end()), inc.findings().size(), inc.affectedEvents());
t.section("Summary without a model");
t.line(s.summarise(inc));
t.section("The prompt a model would receive");
String prompt = s.promptFor(inc);
t.line(prompt.stripTrailing());
int rawChars = f.targetLines.stream().mapToInt(l -> l.length() + 1).sum();
t.section("Size");
t.line("raw target window: %d physical lines, %d characters", f.targetLines.size(), rawChars);
t.line("prompt: %d characters (%.1f%% of the raw window)", prompt.length(), 100.0 * prompt.length() / rawChars);
t.write();
assertThat(incidents).hasSize(1);
assertThat(inc.severity()).isEqualTo("ERROR");
assertThat(prompt.length()).isLessThan(rawChars / 40);
assertThat(prompt).doesNotContain("SQLTransientConnectionException").doesNotContain("\tat ");
}
}
@@ -0,0 +1,124 @@
package com.ankurm.logs;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.junit.jupiter.api.Test;
import com.sun.net.httpserver.HttpServer;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/** The two places a real model plugs in, tested against a stub HTTP server. This proves request and response handling only. */
class ModelSeamsTest {
private static final JsonMapper JSON = JsonMapper.builder().build();
@Test
void anOpenAiCompatibleEmbedderPlugsIntoTheSameDetector() throws Exception {
List<String> seen = new CopyOnWriteArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/v1/embeddings", ex -> {
JsonNode req = JSON.readTree(ex.getRequestBody().readAllBytes());
seen.add(req.toString());
HashingEmbedder inner = new HashingEmbedder(32);
List<java.util.Map<String, Object>> data = new ArrayList<>();
int i = 0;
for (JsonNode text : req.get("input")) {
data.add(java.util.Map.of("index", i++, "embedding", inner.embed(text.asString())));
}
byte[] body = JSON.writeValueAsString(java.util.Map.of("data", data)).getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
try {
Fixtures f = new Fixtures();
OpenAiCompatibleEmbedder remote = new OpenAiCompatibleEmbedder("http://127.0.0.1:" + server.getAddress().getPort() + "/v1", "stub-model", "", 32);
BaselineModel model = new BaselineModel(remote, f.baselineTemplates, 4);
double d = model.distance(f.target("HikariPool-<*> - Connection"));
Transcript t = new Transcript("08-embedder-swap.txt", "The embedder is a seam: a remote one behind a stub /v1/embeddings");
t.line("embedder: %s, dimensions: %d", remote.name(), remote.dimensions());
t.line("HTTP requests while fitting %d baseline templates: %d", f.baselineTemplates.size(), seen.size());
t.line("first request body: %s", seen.getFirst().substring(0, Math.min(150, seen.getFirst().length())) + "...");
t.line("distance of the pool-timeout template through the stub: %.3f", d);
t.line("The stub returns the hashing embedder's own vectors, so this shows the plumbing and says nothing about any real model.");
t.write();
assertThat(seen).hasSize(2); // one request for the baseline templates, one for the new template
assertThat(d).isGreaterThan(0.3);
} finally {
server.stop(0);
}
}
@Test
void aWrongVectorLengthIsRejectedInsteadOfSilentlyMisranking() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/v1/embeddings", ex -> {
byte[] body = "{\"data\":[{\"index\":0,\"embedding\":[0.1,0.2,0.3]}]}".getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
try {
OpenAiCompatibleEmbedder remote = new OpenAiCompatibleEmbedder("http://127.0.0.1:" + server.getAddress().getPort() + "/v1", "m", "", 32);
Throwable err = org.assertj.core.api.Assertions.catchThrowable(() -> remote.embed("hello"));
Transcript t = new Transcript("09-embedder-dimension-mismatch.txt", "A model that returns a different vector length");
t.line("configured dimensions: 32, stub returned 3");
t.line("error: %s", err.getMessage());
t.write();
assertThat(err).isInstanceOf(IllegalStateException.class).hasMessageContaining("expected 32 dimensions");
} finally {
server.stop(0);
}
}
@Test
void theLlmSummarizerSendsTemplatesNotLogLines() throws IOException {
List<String> bodies = new CopyOnWriteArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/v1/chat/completions", ex -> {
bodies.add(new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
byte[] body = JSON.writeValueAsString(java.util.Map.of("choices", List.of(java.util.Map.of("message",
java.util.Map.of("role", "assistant", "content", "STUB REPLY: the pool ran out of connections."))))).getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
try {
Fixtures f = new Fixtures();
Incident inc = new IncidentBuilder(Duration.ofMinutes(10)).build(f.detector.detect(f.target.events())).getFirst();
LlmSummarizer llm = new LlmSummarizer("http://127.0.0.1:" + server.getAddress().getPort() + "/v1", "stub-model", "");
String reply = llm.summarise(inc);
JsonNode sent = JSON.readTree(bodies.getFirst());
Transcript t = new Transcript("10-llm-request.txt", "What the summariser sends to a chat endpoint (stub server)");
t.line("request model: %s, temperature: %s, messages: %d", sent.get("model").asString(), sent.get("temperature"), sent.get("messages").size());
t.line("request content characters: %d", sent.get("messages").get(0).get("content").asString().length());
t.line("contains a stack-trace line: %s", sent.get("messages").get(0).get("content").asString().contains("\tat "));
t.line("reply: %s", reply);
t.line("Not run against a real model. The stub proves the request shape and the reply parsing.");
t.write();
assertThat(reply).startsWith("STUB REPLY");
assertThat(sent.get("messages").get(0).get("content").asString()).contains("Connection is not available").doesNotContain("SQLTransient");
} finally {
server.stop(0);
}
}
}
@@ -0,0 +1,47 @@
package com.ankurm.logs;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
/** Starts a real Spring Boot application, lets it write its own log file, and parses that file. Not synthetic. */
class RealSpringBootLogTest {
@Test
void theParserReadsWhatSpringBootActuallyWrites() throws Exception {
Path log = Path.of("target", "real-springboot.log");
Files.deleteIfExists(log);
try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder(LogAnomalyApplication.class)
.properties("logging.file.name=" + log, "spring.application.name=shop", "server.port=0", "spring.main.banner-mode=off").run()) {
LoggerFactory.getLogger("com.ankurm.shop.OrderController")
.error("Failed to process order 42", new IllegalStateException("quantity must be greater than 0"));
}
List<String> lines = Files.readAllLines(log);
LogParser.Result r = new LogParser().parse(lines.stream());
LogEvent err = r.events().stream().filter(e -> e.level().equals("ERROR")).findFirst().orElseThrow();
Transcript t = new Transcript("12-real-spring-boot-log.txt", "A log file written by Spring Boot 4.2.0 itself (spring.application.name=shop)");
t.section("The first three lines, and the ERROR with its first stack-trace lines");
lines.stream().limit(3).forEach(t::line);
int at = lines.indexOf(lines.stream().filter(l -> l.contains(" ERROR ")).findFirst().orElseThrow());
lines.subList(at, Math.min(at + 4, lines.size())).forEach(t::line);
t.section("Parsed");
t.line("%d physical lines, %d events, %d orphan lines", r.physicalLines(), r.events().size(), r.orphanLines());
t.line("ERROR event: logger=%s message=%s continuation lines=%d", err.shortLogger(), err.message(), err.continuation().size());
t.line("exception line: %s", err.exceptionLine());
t.write();
assertThat(r.orphanLines()).isZero();
assertThat(r.events()).isNotEmpty();
assertThat(err.continuation()).isNotEmpty();
assertThat(err.continuation().getFirst()).as("Spring Boot 4.2 puts a blank line before the stack trace").isEmpty();
assertThat(err.exceptionLine()).startsWith("java.lang.IllegalStateException");
}
}
@@ -0,0 +1,33 @@
package com.ankurm.logs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects lines and writes {@code output/NN-name.txt}, so the test that asserts a fact is the test that records it. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String file;
Transcript(String file, String title) {
this.file = file;
lines.add("# " + title);
}
Transcript line(String s) { lines.add(s); return this; }
Transcript line(String fmt, Object... args) { lines.add(fmt.formatted(args)); return this; }
Transcript blank() { lines.add(""); return this; }
Transcript section(String s) { lines.add(""); lines.add("## " + s); return this; }
void write() throws IOException {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.write(dir.resolve(file), lines);
}
}
+2
View File
@@ -24,6 +24,8 @@
<module>mcp-stateless</module>
<module>code-search-mcp</module>
<module>release-notes-ai</module>
<module>log-anomaly</module>
<module>classic-ml-vs-llm</module>
</modules>
<properties>