Files

216 lines
14 KiB
Java

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 ");
}
}