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:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user