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
This commit is contained in:
2026-12-01 23:51:28 +05:30
co-authored by Claude Sonnet 5.5
parent 943351bccb
commit 489e7b1233
46 changed files with 2047 additions and 0 deletions
@@ -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,57 @@
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 was added in Spring Boot 3.4; 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 (Spring Boot before 3.4)");
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);
}
}