A self-hosted incident-diagnosis engine. When a service breaks, Replay reads your existing telemetry, reconstructs when the incident actually began, and names ranked causes — each claim carrying a citation to a signal you can go and look at.
Documentation: replay-site-seven.vercel.app — quickstart · architecture · grounding · evaluation
Replay is an incident-diagnosis engine you host yourself. It reads the telemetry you already have — Prometheus, Tempo, Loki — plus a webhook where you report your deploys and config changes. When your alerting system says a service is unhealthy, Replay answers four questions in order: which services could be involved, when the trouble actually started, which recent change lines up with that moment, and which logs and spans are worth reading. A model then ranks the likely causes and explains them.
What comes back is a short list of candidates, each pointing at specific signals in your telemetry. A claim that cites nothing real is removed before you ever see it, so the reasoning is something you can check rather than something you have to trust.
Most of this is not the model. Four stages of ordinary code do the narrowing: a graph traversal over trace spans, a change-point detector on latency and error rate, an event correlator that aligns deploys against the moment things turned, and a retrieval budget. The model only ever sees what survives all four, which is roughly fifteen signals and under eight thousand tokens. That ordering is the design, and the rest of this README follows it.
Everything runs inside your network. Telemetry is never sent out, and you supply the model endpoint: any OpenAI-compatible API, Anthropic, or Bedrock. The SaaS alternatives require both — your telemetry in their cloud, and their model.
Replay ranks candidates and shows its evidence. It is not a chatbot, and it never claims a cause is proven.
walkthrough.mp4
A fault is injected at the database, an alert is fired naming the web service, and the pipeline walks from the symptom to the origin. Every stage is visible as it lands — blast radius, inflection, suspects, evidence, verdict. A diagnosis completes in around 30 seconds.
Self-hosted alongside the engine, same origin, same port — the jar serves it.
A production incident produces millions of signals. They do not fit in a context window, they cost a fortune to send, and a model handed an undifferentiated pile of them will confidently invent a cause. So the pile never reaches the model.
The pipeline is a funnel, and each stage is chosen so that its output is smaller and more specific than its input:
| Stage | Kind | In | Out |
|---|---|---|---|
| Trigger | — | an alert webhook | 202, and a pipeline running off-thread |
| Narrow | deterministic | millions of trace spans | ~5 services that could be involved |
| When | deterministic | ~10 metric series | one moment — the inflection |
| Suspects | deterministic | 45 minutes of deploys and config changes | scored candidates, or "nothing correlates" |
| Gather | deterministic | ~2,000 log lines, traces, metric shifts | ~15 signals, each with an id |
| Reason | AI | the packet, ≤ 8,000 tokens | ranked causes as a typed record |
| Gate | deterministic | that record | the same record, minus every claim that cannot cite |
Nothing here is novel, and it should not be — the engineering is in the selection, the parameter choices, and the failure behaviour, all of which are argued for in the sections below.
| Stage | Algorithm | Prior art | What this implementation changed |
|---|---|---|---|
| Narrow | Breadth-first search over an adjacency list | standard graph traversal | layer order chosen for a deferred size cap; cycle guard; min-calls edge threshold |
| When | CUSUM (cumulative sum control chart) | Page, Continuous Inspection Schemes, Biometrika, 1954 | k = 1.0 not the textbook 0.5; ±4σ winsorization; duration-bounded walk-back |
| When | Robust baseline: median + MAD, scaled by 1.4826 | standard robust statistics — 1.4826 is the normal-consistency constant | baseline taken from the first third of the window; ε-floor for all-zero series |
| Suspects | Weighted linear score with an exponential decay kernel e^(−Δt/τ) |
standard time-decay weighting | causal pre-filter before scoring; scope judged by magnitude, not earliest onset |
| Gather | Drain log parsing | He, Zhu, Zheng & Lyu, Drain: An Online Log Parsing Approach with Fixed Depth Tree, ICWS 2017 | (token count, leading tokens) bucket key in place of the fixed-depth parse tree; no miner state persisted between incidents |
| Gather | Greedy budget packing with a reserved head | — | top-3 candidate signals never cut; cuts reported as packet notes |
| Reason | Deterministic set-membership validation | — | one bounded re-ask, accepted only under a monotonicity condition |
Two properties hold across the whole chain, and they matter more than any single stage:
Every stage is decomposable. No stage returns a number nobody can argue with. The correlator returns a score and the named reasons that produced it; the change-point detector returns an onset and the magnitude and steadiness behind it. That is what lets the final report cite things rather than assert them.
Absence is never reported as evidence of quiet. If a telemetry source cannot be read, the packet records a gap. A dead Loki must never look like a service that had nothing to say — that conflation is how a diagnosis quietly becomes fiction.
The alert names one service. That service is very often not the broken one — it is the one whose users noticed. So the first job is to bound the search: which services could plausibly be involved at all?
Trace spans already answer this. Each span records a parent service and a child service, so a window of traces collapses into an adjacency list — the standard directed-graph representation, one service mapped to the services it calls. Walking outward from the alerted service with breadth-first search gives the blast radius: the symptom plus everything reachable downstream.
Three details are load-bearing:
- BFS rather than DFS. Both return the same set today. BFS visits in layer order, so when a size cap is eventually needed for a hub service with hundreds of dependencies, the services it keeps are the closest ones. DFS would keep whatever it wandered into first.
- A cycle guard on visit. Real call graphs are cyclic — retries and callbacks see to that. The set of visited nodes is checked before expanding, not after.
- An edge threshold. Edges carrying fewer than
min-callsrequests are dropped: a rare housekeeping call is not a dependency, and treating it as one drags unrelated services into the radius.
Failure behaviour. If the trace store is unreachable, the radius collapses to the alerted service alone. It does not collapse to an empty graph — an empty graph is a claim that nothing called anything, and that is a lie the rest of the pipeline would believe.
Honest limit: measured blast radius on the demo mesh is 5.0 services out of 5 — zero narrowing. Narrowing only pays off on a mesh wider than this one; on a five-service chain everything is downstream of the entry point. The stage earns its place by producing the graph, which later stages need, more than by shrinking the set.
The alert's timestamp is when a threshold was breached, which is not when the incident began. Between
those two moments sit the scrape interval, the alerting system's for: duration, and however long
the metric took to cross a line. Aligning deploys against the alert time attributes causes to
whatever happened to ship near the wrong moment.
So the engine finds the inflection itself, using CUSUM — the cumulative sum control chart, the
sequential change-detection method introduced by E. S. Page in Continuous Inspection Schemes
(Biometrika, 1954) and standard in statistical process control ever since. The intuition: each sample pours
its strangeness into a bucket, pays a fee k on the way in, and the bucket never goes below empty. A
one-off spike drains away. A sustained shift fills the bucket until it overflows a line h.
z = (x - mu) / sigma, clamped to +-4
S+ = max(0, S+ + z - k) rises
S- = max(0, S- - z - k) falls
Four decisions in this implementation are not the textbook defaults, and each was measured:
muis the median of the first third, andsigmais1.4826 x MAD. Median absolute deviation rather than standard deviation, because a baseline containing one stray spike would otherwise define that spike as normal. The1.4826factor rescales MAD to a normal-distribution sigma.k = 1.0, not the textbook0.5. The textbook pairing assumes a known sigma. Ours is estimated by MAD from a small baseline, which routinely underestimates spread. In a 200-seed sweep over pure-noise windows,k = 0.5false-alarmed about 25% of the time;k = 1.0cut that several fold while still catching a 3-sigma step 198 times out of 200 — and every fault class this detector exists for sits at 3 sigma or far beyond.- Winsorization at ±4 sigma. Without it, one monster sample fills the bucket by itself and sails straight through the sustained-run requirement. Clamping makes the detector alarm on persistence rather than amplitude.
- A leash on the walk-back. The onset is found by walking back from the alarm to the last empty bucket — but on live data an early noise bump kept the bucket off zero and dragged an onset fifteen minutes before the real fault. The backtrack is bounded by a duration (5 minutes), deliberately not a sample count: "5 samples" silently means five minutes at a 60s step and 75 seconds at 15s.
The detector runs over latency and error rate for every service in the blast radius, so an incident produces a set of onsets rather than one. The incident's inflection is their median. Taking the earliest instead rewards whichever series drifted first, which is usually noise — the median survived a live drift ambush that the earliest-onset rule walked straight into.
Measured: on a proper live run at 15-second metric cadence, the detected inflection landed within 19 seconds of the injected fault.
Now there is a moment. Deploys and config changes arrive by webhook and carry their own timestamps, so the question becomes an alignment problem: which of them can causally explain an incident that began then?
The causal filter runs before any scoring. An event after the inflection — plus a grace window — is not a weak candidate, it is a response. It is the rollback. It never receives a score to be merely demoted by; it is excluded outright. Events older than the 45-minute lookback are dropped the same way.
What survives is scored on three named contributions:
score = 0.5 x proximity + 0.3 x scope + 0.2 x corroboration
proximity = e^(-dt / tau), tau = 10 minutes how soon before the inflection
scope = 1.0 broke first | 0.5 in radius | 0.0 outside
corroboration = 1.0 if that service's metrics moved at all
Proximity uses an exponential decay kernel rather than a threshold, so there is no cliff edge
where a deploy 9 minutes 59 seconds out is a suspect and one at 10 minutes 1 second is not. tau = 10m because a bad deploy's symptoms follow it within minutes.
Two subtleties worth defending:
- "Broke first" is judged by the largest magnitude, not the earliest onset. This is the same trap the median fixed one stage earlier: drift-polluted series alarm earliest with tiny magnitudes, while the genuinely faulted service's shift separates by orders of magnitude.
- The grace window is 120 seconds, and it is sized, not tuned. Our own onset estimate was measured running 60–76 seconds early against the true injection time. At the original 30 seconds, genuine deploys landing near the inflection were causally excluded and a stale earlier event stood in and carried the diagnosis. Every extra second also readmits events that truly followed the incident — the rollback we exist to rule out — so it is sized to the measured error and no wider.
An empty list is an answer, not a failure. Resource exhaustion and dependency failures produce no change events at all, and the prompt then states plainly that no deploy correlates. That silence is itself a discriminator: it pushes the diagnosis toward operational causes instead of reaching for the nearest deploy.
When telemetry alone implicates a service that no change event explains, a cascade candidate stands in for it — and it is deduplicated the moment a concrete change explains the same origin. A concrete cause beats an abstract one, and that dedupe rule is what keeps real deploys ranking above a structurally unbeatable stand-in.
Everything so far has narrowed where and when. This stage decides what the model gets to read, and it is the last deterministic step before the only AI call in the system.
Retrieval is bounded and anchored. Logs are queried per suspect, capped at 2,000 lines, over a
window around the anchor — [anchor - 10m, anchor + 5m] — not around now. The minutes before the
inflection carry what led up to it. Spans are fetched once, at the alerted service only: a trace
rooted there already contains the spans of everything it called, so one query covers the radius.
Templating collapses volume into shapes. Two thousand lines of connection to db failed after 912ms are one fact, not two thousand. The engine uses a scoped implementation of Drain (He, Zhu,
Zheng & Lyu, Drain: An Online Log Parsing Approach with Fixed Depth Tree, ICWS 2017 — the parser
behind Drain3, which most log-analytics tooling either uses or imitates): tokenize each message,
replace tokens that are values rather than structure with a wildcard, bucket messages by a key of
(token count, leading tokens), and widen a bucket member's template wherever a joining message
disagrees with it.
That bucket key is this implementation's one substitution for Drain's fixed-depth parse tree, and it
does the same job — a message
is only ever compared against the few templates that open the same way, so cost stays flat as the
template count grows. It also guards against over-merging: connection refused to db after 900ms
cannot fuse with connection timeout to db after 900ms despite agreeing on five of six positions,
and the one word separating a rejected connection from an unanswered one survives.
Miner state is deliberately not persisted across runs. Templates are derived from the incident's own window, so the same incident always yields the same evidence rather than depending on what the process happened to see earlier.
Slots are reserved, not competed for. Five slots go to the busiest shapes and five to the rare ones (seen at most twice), chosen independently. The busiest shapes describe the symptom; a line seen once or twice is often the cause. One budget would let frequency win every time.
The budget cuts from the tail, and says what it cut. Signals are scored from a base per kind, plus
25 if some candidate already implicates that service, plus 20 if the evidence is failure-shaped — an
error log, a failed span. Tokens are estimated at chars / 3.5 (deliberately pessimistic; erring low
costs unused budget, erring high overruns the prompt). The top three candidate signals are
reserved and never cut, because a ranking whose leading entry carries no evidence is worse than a
short packet. Whatever does not fit is reported as a note on the packet rather than dropped silently
— a silent cut reads to the reader as "we looked and there was nothing there."
Everything that survives carries an id, and those ids are the entire basis of the next stage:
chg-<event> a deploy or config change
tel-surge-<svc> a demand-side candidate from telemetry alone
tel-cascade-<svc> a cascade origin with no change to explain it
met-<svc>-<metric> the change point itself, in sigmas and in real units
log-<svc>-<n> a log shape, with a real example line attached
span-<svc>-slow|-error a slow or failed span, with its trace id
The model's job is narrow: rank and explain what the deterministic stages already found, and propose a fix. It is asked once, at temperature 0, through a port the engine types against — so the provider is a starter dependency and a properties change, not a code change.
The answer is a typed record, not prose. Ranked causes with a hypothesis, a blamed service, a
kind, reasoning, a fix, a confidence, and a list of cited signal ids. A malformed response is not a
parse error to paper over: it is retried, bounded, and if the model is unreachable the incident is
still published under a DEGRADED status carrying the packet. An outage costs the diagnosis; it must
not throw away the deterministic stages' work.
Untrusted text is encoded at every prompt boundary. Retrieved log lines are attacker-controlled in the general case — anyone who can write to your logs can write to this prompt. Encoding them closed a vector that was not on the original plan: the first model's output is untrusted input to the second.
This is the priority-one guarantee of the whole project, and it is deliberately boring:
Collect the set of ids in the evidence packet. For each claim, keep the citations that are in that set and strip the ones that are not. If a claim has no citations left, remove the claim.
A set lookup. Not a model checking a model. That is precisely why "100% of report claims cite a real telemetry signal" is a mechanically provable statement rather than a self-graded one — and why CI can fail the build when the grounding rate drops below 100%.
When the gate strips something it reports what it stripped and buys one bounded re-ask, whose result is taken only if it returns at least as many grounded claims as the first answer. That monotonicity condition is the whole safety argument: there is no threshold to tune, and the retry can never make the report worse.
A second, semantic check — does the cited signal actually support the claim? — exists behind
replay.reason.judge-enabled and ships off. It was measured twice and never earned its cost. On
accuracy, the effect was smaller than the run-to-run noise. Against attacker text planted in a
retrieved log, three of three planted lines reached the packet and none became a claim, with the judge
on or off — so whatever refuses those lines, it is not this. It is kept rather than deleted because
the failure it targets is real: the mechanical gate's blind spot is an attacker who borrows a
genuine id, which a set lookup cannot catch by construction.
Measured on a pre-registered corpus, five scenarios per class (CI run 30579638651). A fault injector breaks the demo mesh in a known way, then an alert is fired naming only the service that looks unhealthy — frequently not the one at fault. The engine diagnoses it with no knowledge of what was injected, and because the fault was injected mechanically, nobody grades anything.
| Fault class | Cause in top 3 | |
|---|---|---|
| Bad deploy | 5 / 5 | ranked first on all five |
| Config drift | 5 / 5 | ranked first, class correct on every row |
| Resource exhaustion | 5 / 5 | was 2 / 5 before evidence retrieval |
| Dependency failure | 3 / 5 | the weakest class, and stated as such |
| Grounding | 20 / 20 | every claim cited a signal that resolves |
The two classes that moved most are the argument for the retrieval stage. Resource exhaustion and dependency failure produce no change events at all, so the correlator has nothing to align and no candidate to rank. Every hit on those classes cites only retrieved log and span ids — retrieved evidence carried them alone.
There is no headline accuracy percentage here on purpose. Averaging four classes into one number would hide the weakest, and the weakest is the most informative row on the table.
What these numbers cannot support:
- The corpus is self-generated. These are faults this project chose to inject, in a mesh this project wrote. It measures the engine against a known set of failures, not your production.
- The sample is small. Five scenarios per class. Two runs of an identical configuration have differed by a full row, so a one- or two-row difference is noise, not a result.
- The corpus in this repository is no longer the one that produced this table. It has since been doubled — ten scenarios per class plus five that plant attacker text in a retrieved log — and that corpus has not been measured yet. The table above stands with its run id attached rather than being quietly restated over a corpus it never ran on.
- This run had the semantic judge enabled, which the shipped default does not. Two runs of the shipped configuration totalled 16/20 and 17/20 against this run's 18/20 — inside that noise.
- Two protocols measure two regimes. The fast evaluation alerts seconds after injection at a coarse scrape cadence, so detection has nothing to see yet and the anchor becomes the alert time. A separate protocol runs with a fine cadence and a settling period. Each is honest about one regime; their per-class numbers are not comparable to each other.
You need Docker running, a JDK on Java 25, and an API key for whichever model endpoint you intend to use. The engine boots without a key, but no incident will get past the reasoning stage.
1. Bring up the stack — Postgres, an OpenTelemetry collector, Prometheus, Tempo, Loki, Grafana, and a small instrumented service mesh that exists to be broken.
docker compose -f infra/docker-compose.yml up -d2. Run the engine. The key has to be exported in the same shell. Migrations run on boot, so the database needs no preparation.
export OPENAI_API_KEY=sk-...
export REPLAY_AUTH_OPERATOR_PASSWORD=pick-something
cd replay-engine && ./mvnw spring-boot:runThe dashboard is served by the engine itself at http://localhost:8080. If you skip the password, one is generated per run and printed to the log — there is no built-in default, deliberately.
3. Break something. The mesh is a chain: web → checkout → payments, inventory → db. Each
service exposes a fault hook. Injecting latency at the database and then alerting on web is the
clearest first run, because the alert names a service that is not the cause.
curl -X POST localhost:8005/_fault \
-H 'content-type: application/json' \
-d '{"mode": "latency", "delay_ms": 2000}'4. Wait three or four minutes, then fire the alert. The mesh exports metrics every 60 seconds; alerting immediately leaves change-point detection with no post-shift samples to find.
curl -u operator:$REPLAY_AUTH_OPERATOR_PASSWORD \
-X POST localhost:8080/api/v1/alerts \
-H 'content-type: application/json' \
-d "{\"service\": \"web\", \"alertName\": \"HighLatency\",
\"startedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"The alert is accepted immediately and the pipeline runs asynchronously. Open the dashboard and the
incident appears with its stages filling in as each one lands. Turn the fault off with
{"mode": "off"} when you are done, or the mesh stays slow.
Give it a quiet window. Change-point detection needs a baseline it can call normal. A build, a test suite, or a second fault injection running at the same time moves mesh latency enough to pollute that baseline. One fault per window, and the window is 45 minutes from the end of the last disturbance.
The quickstart on the docs site covers the same ground with more room, including what each fault mode does and why the wait matters.
Local to production is a configuration change, not a code change. Nothing is hardcoded; everything below reads from properties or the environment, and the three telemetry URLs are also editable from the dashboard. The full list is in configuration, and self-hosting covers deployment.
| Property | What it is |
|---|---|
replay.prometheus.url / replay.tempo.url / replay.loki.url |
Where your telemetry lives |
spring.datasource.* |
Postgres connection |
spring.ai.openai.* |
Model endpoint, model name, timeout, retries |
replay.when.latency-query / .error-query / .traffic-query |
PromQL templates, not code. The bundled metric names are OpenTelemetry-semconv-era artifacts; a different tracing stack names them differently without being any less correct. |
replay.when.window / .step |
Detection window and resolution |
replay.suspects.grace |
How long after the estimated inflection a change may still be credited |
replay.gather.token-budget |
The prompt ceiling |
GET /api/v1/config returns the resolved configuration through an allowlist — a denylist would
leak the next property somebody adds.
Access control. HTTP Basic, two roles, because two very different callers reach this API: a person opening a dashboard, and an alerting system that cannot fill in a login form.
OPERATOR— everything, including the dashboard, the metrics and the API description.INGEST—POST /api/v1/alertsandPOST /api/v1/changes, and nothing else. An alerting system needs to report that something broke; it has no business reading the history of everything that ever broke.
Basic sends the credential on every request, encoded but not encrypted. Terminate TLS in front of this, and for anything larger than one team put an identity-aware proxy there instead.
Interactive documentation at /swagger-ui.html; health and Prometheus metrics at
/actuator/health and /actuator/prometheus.
| Method | Path | |
|---|---|---|
POST |
/api/v1/alerts |
Trigger a diagnosis. 202, then the pipeline runs asynchronously. |
POST |
/api/v1/changes |
Report a deploy or config change for the correlator to align against. |
GET |
/api/v1/incidents |
The incident feed, ordered by receipt. |
GET |
/api/v1/incidents/{id} |
The full report: causes, citations, evidence packet, stage timings, gaps. |
GET |
/api/v1/services · /topology · /changes · /connections · /config |
What the engine can see and how it is pointed. |
PUT |
/api/v1/connections/{id} |
Repoint a telemetry source. |
replay-engine/ Spring Boot engine — the pipeline, the stores, the API
graph/ trace-derived dependency graph and blast radius (NARROW)
changepoint/ CUSUM change-point detection (WHEN)
correlate/ weighted-score event correlation (SUSPECTS)
gather/ log templating, evidence collection, budgeting (GATHER)
reason/ the model port, the prompt, and the grounding gates
ui/ Vite + React 19 + TypeScript dashboard, built into the engine's jar
demo-mesh/ instrumented FastAPI mesh with fault hooks — the substrate for the metric
infra/ Docker Compose: Postgres, the LGTM stack, the mesh
replay-site/ the documentation site (replay-site-seven.vercel.app)
docs/diagrams/ the architecture and per-stage diagrams above
docs/DESIGN.html the design document
One image serves both the engine and the dashboard, same origin, one port:
docker build -f replay-engine/Dockerfile -t replay .cd replay-engine && ./mvnw test # hermetic; Testcontainers, so Docker must be running
cd ui && npm test # vitestThe evaluation harness is named outside the normal test patterns on purpose, because it spends real model tokens. It has to be asked for:
cd replay-engine && ./mvnw -Dtest=EvalRun testCI runs four jobs on every push — build, ui, eval and onset-eval — and a grounding rate
below 100% fails the build.
Stated rather than left to be discovered:
- Retry storms and cascading amplification are registered, not implemented. They are a known fault class this engine does not yet diagnose.
- Dependency failure sits at 3/5. That is the number to argue with.
- Narrowing has never been measured as a win — blast radius on the demo mesh is the whole mesh.
- The semantic judge ships off and the mechanical gate's blind spot — a borrowed, genuine signal id — is open.
- The strip-and-re-ask path in the grounding gate has never fired across the corpus. It is insurance, not a measured win.
MIT — see LICENSE.











