diff --git a/README.md b/README.md index bd3f083..baa322c 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ facts, so the build fails when a claim stops being true. | `mcp-stateless` | MCP 2026-07-28 for Java Developers: Migrating an MCP Server to the Stateless Spec | one order server as a 2025-era stateful and a 2026-07-28 stateless Spring AI server, behind a round-robin balancer, with multi-round-trip requests, a version router and real SDK clients | | `code-search-mcp` | Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings) | JavaParser indexes a four-module sample monorepo, a swappable `Embedder` (offline hashing or any `/v1/embeddings` endpoint) ranks methods by what they do, `find_usages` compares name matching with the symbol solver, and the three tools are served on the 2026-07-28 stateless spec with the 2.2.0 modern SDK, tested over raw HTTP, two server instances and the SDK client | | `release-notes-ai` | AI Release Notes and PR Descriptions in Java: JGit, Spring AI and Gitea | JGit reads a real repository, commits are grouped by Conventional Commit type, release notes and a version bump are computed in code, a Spring AI model writes only the opening paragraph behind a guard that rejects invented PR numbers and hashes, and a Gitea client creates or updates the release and PR so a rerun edits instead of failing; tested with a stub model and a local fake Gitea | +| `log-anomaly` | AI Log Anomaly Detection for Spring Boot: Embeddings and Clustering | a parser for Spring Boot's own log layout, template mining, an `Embedder` seam (offline hashing or any `/v1/embeddings` endpoint), k-means over normal templates, a novel-template detector and a rate-spike detector with their measured blind spots, incidents, and a summary prompt that is 0.4% of the raw window; tested on seeded synthetic logs and on a log file Spring Boot 4.2.0 wrote itself | ## Versions (verified on Maven Central, 2026-10-11) @@ -46,6 +47,7 @@ facts, so the build fails when a claim stops being true. | Claude Code CLI | 2.1.330 | `claude mcp` run for `claude-code-spring/output/08`; the model-side behaviour is documented, not executed | | Spring Boot / Spring AI / MCP Java SDK (`mcp-stateless`) | 4.2.0 / 2.1.0 / 2.2.0 | verified on Maven Central 2026-11-22; this module overrides the Spring versions above | | MCP Java SDK / JavaParser (`code-search-mcp`) | 2.2.0 / 3.28.2 | verified on Maven Central 2026-11-25; `code-search-mcp` only. The 2026-07-28 "modern" server API (`io.modelcontextprotocol.modern`) is in `mcp-core` 2.2.0; JavaParser 3.28.2 cannot resolve calls to implicit record accessors | +| Spring Boot (`log-anomaly`) | 4.2.0 | verified on Maven Central 2026-12-01; `log-anomaly` only. No Spring AI and no model download: the embedder and the summariser are seams, tested offline | | JDK | 25 LTS | | | JUnit | 6.1.3 | | diff --git a/log-anomaly/README.md b/log-anomaly/README.md new file mode 100644 index 0000000..660138b --- /dev/null +++ b/log-anomaly/README.md @@ -0,0 +1,30 @@ +# log-anomaly + +Log anomaly detection for a Spring Boot application, in plain Java 25 and Spring Boot 4.2.0. A baseline log is parsed, +reduced to message templates, embedded, and grouped with k-means. A new log is then checked two ways: a template that +never occurred and is far from every normal cluster is a **novel template**; a template that did occur but arrives far +above its baseline rate is a **rate spike**. Findings that overlap in time become one incident with a short summary. + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn test -pl log-anomaly # writes output/01..12 (00 is the QuickStart run) +bash log-anomaly/scripts/run-all.sh # also packages the jar and writes output/13 with curl +java log-anomaly/quickstart/QuickStart.java # the whole idea in one file, no Maven +``` + +| Class | Role | +|---|---| +| `LogParser`, `LogEvent` | Spring Boot's default layout, with or without the application name; stack traces folded into one event | +| `TemplateMiner` | masks numbers and ids; an optional second pass wildcards words that vary (user names) | +| `Embedder`, `HashingEmbedder`, `OpenAiCompatibleEmbedder` | the seam: offline word hashing, or any `/v1/embeddings` endpoint | +| `KMeans`, `BaselineModel` | spherical k-means over baseline templates; distance = 1 - cosine to the nearest centre | +| `AnomalyDetector`, `Finding` | the novel-template and rate-spike detectors | +| `IncidentBuilder`, `Incident` | findings close in time become one incident | +| `IncidentSummarizer`, `TemplateSummarizer`, `LlmSummarizer` | a no-model summary, and a chat-endpoint summary that is sent templates, never raw lines | +| `SyntheticLogs`, `SampleLogWriter` | the seeded generator behind the tests (synthetic: see the class Javadoc) | +| `AnalysisService`, `AnomalyController`, `LogAnomalyApplication` | `GET /api/incidents?baseline=&target=` (demo only, it reads any path the server can read) | + +`output/` holds the transcripts the tests write; every figure in the post is quoted from there. Files 12 and 13 contain +timestamps and process ids that change on every run. The hashing embedder compares words, not meaning, so the numbers +in `output/03` and `output/04` describe that embedder only. `OpenAiCompatibleEmbedder` and `LlmSummarizer` were tested +against stub servers and have not been run against a real model. diff --git a/log-anomaly/output/00-quickstart.txt b/log-anomaly/output/00-quickstart.txt new file mode 100644 index 0000000..933c271 --- /dev/null +++ b/log-anomaly/output/00-quickstart.txt @@ -0,0 +1,10 @@ +$ java QuickStart.java +normal lines: 6, normal templates: 4 + Order <*> placed by customer c-<*> + Payment approved for order <*> in <*> ms + Reserved <*> units of SKU-<*> + Token validated for user u-<*> + +0.000 known template Order <*> placed by customer c-<*> +0.764 NEW and FAR from normal HikariPool-<*> - Connection is not available, request timed out after <*>ms. +0.225 new but close to normal Payment approved for order <*> in <*> ms but ledger write failed diff --git a/log-anomaly/output/01-parse.txt b/log-anomaly/output/01-parse.txt new file mode 100644 index 0000000..ebe070d --- /dev/null +++ b/log-anomaly/output/01-parse.txt @@ -0,0 +1,21 @@ +# Parsing Spring Boot log lines + +## First lines of the baseline +2026-11-30T09:00:00.000+05:30 INFO 4121 --- [shop] [nio-8080-exec-6] c.a.shop.CatalogController : GET /api/products/884 200 in 13 ms +2026-11-30T09:00:01.843+05:30 INFO 4121 --- [shop] [nio-8080-exec-6] c.a.shop.OrderController : Order 77525 placed by customer c-519 total=8093.82 +2026-11-30T09:00:03.687+05:30 INFO 4121 --- [shop] [nio-8080-exec-4] c.a.shop.CatalogController : GET /api/products/476 200 in 35 ms + +## An ERROR with a stack trace: one event, several physical lines +2026-11-30T11:12:30.421+05:30 ERROR 4121 --- [shop] [nio-8080-exec-8] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Connection is not available, request timed out after 30000ms. +java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms. + at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:686) + at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:179) + +## Counts +baseline: 3947 physical lines, 3857 events, 0 orphan lines +target: 2196 physical lines, 1524 events, 0 orphan lines +that ERROR event: level=ERROR logger=HikariPool continuation lines=3 +exception line: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms. + +## The same line without the application name bracket +parsed: level=INFO thread=nio-8080-exec-1 logger=OrderController message=Order 42 placed diff --git a/log-anomaly/output/02-templates.txt b/log-anomaly/output/02-templates.txt new file mode 100644 index 0000000..f713be2 --- /dev/null +++ b/log-anomaly/output/02-templates.txt @@ -0,0 +1,20 @@ +# Template mining + +## Baseline: 3857 events become 10 templates + 791 INFO CatalogController GET /api/products/<*> <*> in <*> ms + 746 INFO AuthFilter Token validated for user u-<*> + 715 INFO OrderController Order <*> placed by customer c-<*> total=<*> + 695 INFO InventoryService Reserved <*> units of SKU-<*> + 653 INFO PaymentService Payment approved for order <*> in <*> ms + 120 INFO HikariPool HikariPool-<*> - Pool stats (total=<*>, active=<*>, idle=<*>, waiting=<*>) + 62 WARN PaymentService Payment declined for order <*>: insufficient funds + 43 WARN SlowQueryDetector Slow query (<*> ms): select * from orders where customer_id = ? + 30 ERROR OrderController Failed to process order <*>: validation failed + 2 INFO CacheRefresher Nightly cache refresh completed in <*> ms + +## Failure: words that are not numbers. Same traffic, real user names instead of u-1042 +AuthFilter templates, digits-only masking: 20 +AuthFilter templates, with the second pass: 1 +all templates, digits-only masking: 29 +all templates, with the second pass: 10 + 746 Token validated for user <*> diff --git a/log-anomaly/output/03-embeddings.txt b/log-anomaly/output/03-embeddings.txt new file mode 100644 index 0000000..9dbc952 --- /dev/null +++ b/log-anomaly/output/03-embeddings.txt @@ -0,0 +1,21 @@ +# What a hashing embedder considers close (distance = 1 - cosine) +distance 0.415 + A: WARN PaymentService Payment declined for order <*>: insufficient funds + B: INFO PaymentService Payment approved for order <*> in <*> ms + +distance 0.249 + A: ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection + B: ERROR OrderController Failed to process order <*>: validation failed + +distance 0.853 + A: ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection + B: ERROR HikariPool Could not get a database connection from the pool + +distance 0.118 + A: INFO PaymentService Payment approved for order <*> in <*> ms + B: INFO PaymentService Payment approved for order <*> in <*> ms but ledger write failed + +distance 1.000 + A: INFO AuthFilter Token validated for user u-<*> + B: ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms. + diff --git a/log-anomaly/output/04-clusters.txt b/log-anomaly/output/04-clusters.txt new file mode 100644 index 0000000..954abcb --- /dev/null +++ b/log-anomaly/output/04-clusters.txt @@ -0,0 +1,25 @@ +# k decides how far from normal a template can be + +## Baseline templates grouped with k = 4 +cluster 0: + INFO CatalogController GET /api/products/<*> <*> in <*> ms (distance to centre 0.325) + INFO InventoryService Reserved <*> units of SKU-<*> (distance to centre 0.325) + INFO CacheRefresher Nightly cache refresh completed in <*> ms (distance to centre 0.321) +cluster 1: + INFO OrderController Order <*> placed by customer c-<*> total=<*> (distance to centre 0.343) + INFO PaymentService Payment approved for order <*> in <*> ms (distance to centre 0.212) + WARN PaymentService Payment declined for order <*>: insufficient funds (distance to centre 0.315) + ERROR OrderController Failed to process order <*>: validation failed (distance to centre 0.339) +cluster 2: + INFO AuthFilter Token validated for user u-<*> (distance to centre 0.239) + INFO HikariPool HikariPool-<*> - Pool stats (total=<*>, active=<*>, idle=<*>, waiting=<*>) (distance to centre 0.239) +cluster 3: + WARN SlowQueryDetector Slow query (<*> ms): select * from orders where customer_id = ? (distance to centre 0.000) + +## Distance of the five new templates, and the threshold, for different k (threshold = worst baseline distance + 0.05) +k worst-normal threshold | hikari jdbc gateway reword ledger-fail +1 0.677 0.727 | 0.747* 0.629 0.623 0.470 0.368 +2 0.564 0.614 | 0.726* 0.477 0.471 0.410 0.305 +4 0.343 0.393 | 0.678* 0.434* 0.459* 0.394* 0.256 +10 0.000 0.050 | 0.510* 0.249* 0.401* 0.101* 0.118* +(* = flagged at that threshold) diff --git a/log-anomaly/output/05-detection.txt b/log-anomaly/output/05-detection.txt new file mode 100644 index 0000000..0e41fcb --- /dev/null +++ b/log-anomaly/output/05-detection.txt @@ -0,0 +1,18 @@ +# Findings for the 30-minute target window (incident starts at minute 12) +threshold 0.393 (worst baseline distance 0.343 + margin 0.05), k = 4 + +## Flagged +NOVEL_TEMPLATE ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms. x144 new template, distance 0.678 > 0.393 +NOVEL_TEMPLATE WARN PaymentService Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> x90 new template, distance 0.459 > 0.393 +NOVEL_TEMPLATE ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection x108 new template, distance 0.434 > 0.393 +NOVEL_TEMPLATE INFO OrderController Order <*> placed by customer c-<*> total=<*> currency=INR x156 new template, distance 0.394 > 0.393 +RATE_SPIKE WARN PaymentService Payment declined for order <*>: insufficient funds x44 peak 44 per 5 min vs baseline mean 2.6 (std 0.9), z = 45.6 + +## Not flagged, although something is wrong +pool stats template known to the baseline: true + during the incident: HikariPool-1 - Pool stats (total=10, active=10, idle=0, waiting=32) + during normal times: HikariPool-1 - Pool stats (total=10, active=2, idle=8, waiting=0) +'but ledger write failed' has distance 0.256, threshold 0.393, so it is NOT flagged + +## Flagged, although nothing is wrong +the deployment's reworded order line has distance 0.394 against threshold 0.393 diff --git a/log-anomaly/output/06-threshold-sweep.txt b/log-anomaly/output/06-threshold-sweep.txt new file mode 100644 index 0000000..e29eae0 --- /dev/null +++ b/log-anomaly/output/06-threshold-sweep.txt @@ -0,0 +1,11 @@ +# What each margin flags, k = 4 +worst baseline distance: 0.343 +margin 0.00 -> threshold 0.343 -> 4 of 5 new templates flagged: Order <*> | HikariPool-<*> - | Failed to | Payment gateway +margin 0.05 -> threshold 0.393 -> 4 of 5 new templates flagged: Order <*> | HikariPool-<*> - | Failed to | Payment gateway +margin 0.10 -> threshold 0.443 -> 2 of 5 new templates flagged: HikariPool-<*> - | Payment gateway +margin 0.20 -> threshold 0.543 -> 1 of 5 new templates flagged: HikariPool-<*> - + +## Ranking is more trustworthy than the cut-off +the three real new templates score 0.678, 0.434, 0.459 +the harmless reword scores 0.394, so it ranks below all three +a threshold between 0.394 and 0.434 would split them, but it is chosen after seeing the answer diff --git a/log-anomaly/output/07-incident.txt b/log-anomaly/output/07-incident.txt new file mode 100644 index 0000000..aeb5f17 --- /dev/null +++ b/log-anomaly/output/07-incident.txt @@ -0,0 +1,22 @@ +# From findings to one incident and one summary +5 findings -> 1 incident(s) +window 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30, 5 findings, 542 events + +## Summary without a model +ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x). + +## The prompt a model would receive +You are helping an on-call engineer. Below are the anomalous log templates from one incident. +Write 3 sentences: what changed, the likely cause, and what to check first. +Only use facts from the list; do not invent hosts, versions or numbers. + +Window: 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30 +1. [ERROR] HikariPool: HikariPool-<*> - Connection is not available, request timed out after <*>ms. (NOVEL_TEMPLATE, 144 events, new template, distance 0.678 > 0.393) +2. [WARN] PaymentService: Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> (NOVEL_TEMPLATE, 90 events, new template, distance 0.459 > 0.393) +3. [ERROR] OrderController: Failed to process order <*>: Unable to acquire JDBC Connection (NOVEL_TEMPLATE, 108 events, new template, distance 0.434 > 0.393) +4. [INFO] OrderController: Order <*> placed by customer c-<*> total=<*> currency=INR (NOVEL_TEMPLATE, 156 events, new template, distance 0.394 > 0.393) +5. [WARN] PaymentService: Payment declined for order <*>: insufficient funds (RATE_SPIKE, 44 events, peak 44 per 5 min vs baseline mean 2.6 (std 0.9), z = 45.6) + +## Size +raw target window: 2196 physical lines, 310589 characters +prompt: 1112 characters (0.4% of the raw window) diff --git a/log-anomaly/output/08-embedder-swap.txt b/log-anomaly/output/08-embedder-swap.txt new file mode 100644 index 0000000..ec7d443 --- /dev/null +++ b/log-anomaly/output/08-embedder-swap.txt @@ -0,0 +1,6 @@ +# The embedder is a seam: a remote one behind a stub /v1/embeddings +embedder: openai-compatible:stub-model, dimensions: 32 +HTTP requests while fitting 10 baseline templates: 2 +first request body: {"model":"stub-model","input":["INFO CatalogController GET /api/products/<*> <*> in <*> ms","INFO AuthFilter Token validated for user u-<*>","INFO Ord... +distance of the pool-timeout template through the stub: 0.520 +The stub returns the hashing embedder's own vectors, so this shows the plumbing and says nothing about any real model. diff --git a/log-anomaly/output/09-embedder-dimension-mismatch.txt b/log-anomaly/output/09-embedder-dimension-mismatch.txt new file mode 100644 index 0000000..6a376fc --- /dev/null +++ b/log-anomaly/output/09-embedder-dimension-mismatch.txt @@ -0,0 +1,3 @@ +# A model that returns a different vector length +configured dimensions: 32, stub returned 3 +error: expected 32 dimensions but the model returned 3 diff --git a/log-anomaly/output/10-llm-request.txt b/log-anomaly/output/10-llm-request.txt new file mode 100644 index 0000000..3cf5490 --- /dev/null +++ b/log-anomaly/output/10-llm-request.txt @@ -0,0 +1,6 @@ +# What the summariser sends to a chat endpoint (stub server) +request model: stub-model, temperature: 0, messages: 1 +request content characters: 1112 +contains a stack-trace line: false +reply: STUB REPLY: the pool ran out of connections. +Not run against a real model. The stub proves the request shape and the reply parsing. diff --git a/log-anomaly/output/11-endpoint.txt b/log-anomaly/output/11-endpoint.txt new file mode 100644 index 0000000..a2ab410 --- /dev/null +++ b/log-anomaly/output/11-endpoint.txt @@ -0,0 +1,10 @@ +# GET /api/incidents on a running Spring Boot application +HTTP 200 +baselineLines=3947 targetLines=2196 baselineTemplates=10 targetTemplates=14 clusters=4 threshold=0.393 +incidents: 1 + NOVEL_TEMPLATE ERROR x144 HikariPool-<*> - Connection is not available, request timed out after <*>ms. + NOVEL_TEMPLATE WARN x90 Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> + NOVEL_TEMPLATE ERROR x108 Failed to process order <*>: Unable to acquire JDBC Connection + NOVEL_TEMPLATE INFO x156 Order <*> placed by customer c-<*> total=<*> currency=INR + RATE_SPIKE WARN x44 Payment declined for order <*>: insufficient funds +summary: ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x). diff --git a/log-anomaly/output/12-real-spring-boot-log.txt b/log-anomaly/output/12-real-spring-boot-log.txt new file mode 100644 index 0000000..4d6780b --- /dev/null +++ b/log-anomaly/output/12-real-spring-boot-log.txt @@ -0,0 +1,15 @@ +# A log file written by Spring Boot 4.2.0 itself (spring.application.name=shop) + +## The first three lines, and the ERROR with its first stack-trace lines +2026-12-01T23:53:34.953+05:30 INFO 12412 --- [shop] [main] o.a.maven.surefire.booter.ForkedBooter : Starting ForkedBooter v3.5.4 using Java 25.0.5.1 with PID 12412 (started by root in /tmp/work/java-ai-agents/log-anomaly) +2026-12-01T23:53:34.975+05:30 INFO 12412 --- [shop] [main] o.a.maven.surefire.booter.ForkedBooter : No active profile set, falling back to 1 default profile: "default" +2026-12-01T23:53:37.369+05:30 INFO 12412 --- [shop] [main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 0 (http) +2026-12-01T23:53:38.561+05:30 ERROR 12412 --- [shop] [main] com.ankurm.shop.OrderController : Failed to process order 42 + +java.lang.IllegalStateException: quantity must be greater than 0 + at com.ankurm.logs.RealSpringBootLogTest.theParserReadsWhatSpringBootActuallyWrites(RealSpringBootLogTest.java:23) ~[test-classes/:na] + +## Parsed +96 physical lines, 11 events, 0 orphan lines +ERROR event: logger=OrderController message=Failed to process order 42 continuation lines=85 +exception line: java.lang.IllegalStateException: quantity must be greater than 0 diff --git a/log-anomaly/output/13-jar-curl.txt b/log-anomaly/output/13-jar-curl.txt new file mode 100644 index 0000000..14ed029 --- /dev/null +++ b/log-anomaly/output/13-jar-curl.txt @@ -0,0 +1,14 @@ +# The packaged jar answering curl +$ java -jar target/log-anomaly.jar --server.port=18080 & +$ curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log" +{ + "baselineLines": 3947, + "targetLines": 2196, + "baselineTemplates": 10, + "targetTemplates": 14, + "clusters": 4 +} +ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x). + +$ curl -s -o /dev/null -w "%{http_code}" "localhost:18080/api/incidents?baseline=missing.log&target=missing.log" +500 diff --git a/log-anomaly/pom.xml b/log-anomaly/pom.xml new file mode 100644 index 0000000..af536ef --- /dev/null +++ b/log-anomaly/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + + com.ankurm.agents + java-ai-agents + 1.0.0 + + + log-anomaly + Log anomaly detection for Spring Boot: template mining, embeddings, clustering and an incident summary + + + + 4.2.0 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + log-anomaly + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + repackage + + + + + diff --git a/log-anomaly/quickstart/QuickStart.java b/log-anomaly/quickstart/QuickStart.java new file mode 100644 index 0000000..9925384 --- /dev/null +++ b/log-anomaly/quickstart/QuickStart.java @@ -0,0 +1,64 @@ +// Run with: java QuickStart.java (JDK 21 or newer, no Maven, no libraries) +// +// The whole idea in one file: mask the changing parts of each log line to get a template, turn every template into +// a vector of hashed words, and measure how far a new template is from the closest "normal" one. +import java.util.*; +import java.util.regex.Pattern; + +public class QuickStart { + + static final Pattern NUMBER = Pattern.compile("(?"); + } + + /** Step 2: a template becomes a unit-length vector by hashing its words into 64 buckets. */ + static double[] embed(String text) { + double[] v = new double[64]; + for (String w : text.toLowerCase().split("[^a-z]+")) { + if (w.length() > 1) { + int h = w.hashCode(); + v[Math.floorMod(h, 64)] += (h >>> 31) == 0 ? 1 : -1; + } + } + double norm = Math.sqrt(Arrays.stream(v).map(x -> x * x).sum()); + for (int i = 0; i < v.length; i++) v[i] /= norm; + return v; + } + + /** Step 3: distance = 1 - cosine similarity. 0 means the same words, 1 means no words in common. */ + static double distance(double[] a, double[] b) { + double dot = 0; + for (int i = 0; i < a.length; i++) dot += a[i] * b[i]; + return 1 - dot; + } + + public static void main(String[] args) { + List normal = List.of( + "Order 42 placed by customer c-17", "Order 43 placed by customer c-90", + "Payment approved for order 42 in 80 ms", "Payment approved for order 43 in 95 ms", + "Reserved 2 units of SKU-1001", "Token validated for user u-1001"); + List today = List.of( + "Order 51 placed by customer c-3", + "HikariPool-1 - Connection is not available, request timed out after 30000ms.", + "Payment approved for order 52 in 90 ms but ledger write failed"); + + Set known = new LinkedHashSet<>(); + normal.forEach(m -> known.add(template(m))); + System.out.println("normal lines: " + normal.size() + ", normal templates: " + known.size()); + known.forEach(t -> System.out.println(" " + t)); + + Map vectors = new LinkedHashMap<>(); + known.forEach(t -> vectors.put(t, embed(t))); + + System.out.println(); + for (String line : today) { + String t = template(line); + double nearest = vectors.values().stream().mapToDouble(v -> distance(embed(t), v)).min().orElseThrow(); + String verdict = known.contains(t) ? "known template" : nearest > 0.5 ? "NEW and FAR from normal" : "new but close to normal"; + System.out.printf("%.3f %-24s %s%n", nearest, verdict, t); + } + } +} diff --git a/log-anomaly/scripts/run-all.sh b/log-anomaly/scripts/run-all.sh new file mode 100755 index 0000000..22c7d61 --- /dev/null +++ b/log-anomaly/scripts/run-all.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Regenerates every file in output/: the tests write 01-12, the packaged jar plus curl writes 13. +# Timestamps, PIDs and timings in 12 and 13 differ on every run; the numbers in 01-11 do not. +set -eu +cd "$(dirname "$0")/.." +mvn -B -q -f ../pom.xml -pl log-anomaly package +java -cp target/classes com.ankurm.logs.SampleLogWriter target/sample-logs +{ + echo "# The packaged jar answering curl" + echo '$ java -jar target/log-anomaly.jar --server.port=18080 &' + java -jar target/log-anomaly.jar --server.port=18080 --spring.main.banner-mode=off > target/jar.log 2>&1 & + PID=$! + trap 'kill $PID 2>/dev/null || true' EXIT + for i in $(seq 1 60); do curl -s -o /dev/null "localhost:18080/api/incidents" && break; sleep 1; done + echo '$ curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log"' + curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log" \ + | python3 -c 'import json,sys; d=json.load(sys.stdin); print(json.dumps({k:d[k] for k in ("baselineLines","targetLines","baselineTemplates","targetTemplates","clusters")}, indent=2)); print(d["summaries"][0])' + echo + echo '$ curl -s -o /dev/null -w "%{http_code}" "localhost:18080/api/incidents?baseline=missing.log&target=missing.log"' + curl -s -o /dev/null -w "%{http_code}\n" "localhost:18080/api/incidents?baseline=missing.log&target=missing.log" +} > output/13-jar-curl.txt +echo "wrote output/13-jar-curl.txt" diff --git a/log-anomaly/src/main/java/com/ankurm/logs/AnalysisService.java b/log-anomaly/src/main/java/com/ankurm/logs/AnalysisService.java new file mode 100644 index 0000000..91ddfed --- /dev/null +++ b/log-anomaly/src/main/java/com/ankurm/logs/AnalysisService.java @@ -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 incidents, List 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 a = Files.lines(baselineLog); Stream 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 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()); + } +} diff --git a/log-anomaly/src/main/java/com/ankurm/logs/AnomalyController.java b/log-anomaly/src/main/java/com/ankurm/logs/AnomalyController.java new file mode 100644 index 0000000..6bd2bed --- /dev/null +++ b/log-anomaly/src/main/java/com/ankurm/logs/AnomalyController.java @@ -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)); + } +} diff --git a/log-anomaly/src/main/java/com/ankurm/logs/AnomalyDetector.java b/log-anomaly/src/main/java/com/ankurm/logs/AnomalyDetector.java new file mode 100644 index 0000000..13cb7e2 --- /dev/null +++ b/log-anomaly/src/main/java/com/ankurm/logs/AnomalyDetector.java @@ -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: + *
    + *
  • Novel template — the template never occurred in the baseline and its embedding is + * farther than {@code distanceThreshold} from every baseline cluster. Finds new kinds of messages.
  • + *
  • Rate spike — 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.
  • + *
+ */ +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 baselineRate; // template key -> {mean, std} per bucket + + public AnomalyDetector(BaselineModel baseline, TemplateMiner miner, List 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 rates(List 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 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 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 detect(List target) { + List out = new ArrayList<>(novel(target)); + out.addAll(spikes(target)); + out.sort(Finding.BY_PRIORITY); + return out; + } + + public List novel(List target) { + List 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 spikes(List target) { + Instant start = target.getFirst().timestamp(); + Map 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 byKey = new HashMap<>(); + for (Template t : miner.mine(target)) { + byKey.put(t.key(), t); + } + List 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 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}; + } +} diff --git a/log-anomaly/src/main/java/com/ankurm/logs/BaselineModel.java b/log-anomaly/src/main/java/com/ankurm/logs/BaselineModel.java new file mode 100644 index 0000000..0535433 --- /dev/null +++ b/log-anomaly/src/main/java/com/ankurm/logs/BaselineModel.java @@ -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 distance 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