Embedding-Based Pattern Detection in Agent Failure Streams
Vector embeddings reveal recurring agent failures that traditional logs and rules miss.

Embedding-based pattern detection automatically groups recurring AI agent failures by projecting trace behavior into vector space, clustering similar deviations, and labeling groups for remediation. This approach surfaces repeated misbehavior that error logs and fixed rules miss. It stays useful as those groups become targeted fixes and regression tests, while other checks catch failures that look like successful behavior.
Why agent failure streams are different from application error streams
A tool call can return 200 while the agent fabricates an identifier or promises a non-existent refund. The infrastructure has succeeded. The agent has not. Traditional monitors detect exceptions, status codes, and latency spikes, but these signals do not show whether the agent did what its instructions said to do.
Microsoft AI Red Team's v2.0 taxonomy identifies Goal Hijacking, Session Context Contamination, and MCP/Plugin Abuse among the failure modes that can leave execution looking successful. Their effects can also spread beyond the step where they begin. An injected or flawed step corrupts downstream agents and tool calls that depend on its output. Inspecting each step independently therefore misses the dependency chain through which the failure propagates.
What a failure stream actually contains, and why its structure matters for detection
An agent failure stream consists of multi-step, semi-structured spans, with evidence distributed across role assignments, tool sequences, argument shapes, and natural-language content. A trace can include the system prompt, a plan step, a tool invocation and its arguments, the response, reasoning over that response, and the final output. No single field captures the whole failure. A role-inconsistent delegation or abnormal artifact-to-agent influence pattern is visible only in how the spans relate to one another.
For MCP tool-description poisoning, a rule would need to distinguish legitimate descriptive content from instructions that redirect the agent. Matching an exact argument shape would not capture that semantic intent. Matching particular words would require anticipating the different ways malicious instructions could be expressed and the contexts in which they affect behavior. The rule would also need to connect the description to the agent actions it influenced. Fixed rules become difficult to maintain as tool pathways and natural-language content change, which makes a representation of shared behavior more useful than an expanding catalog of literal matches.
How projecting trace segments into vector space makes semantic similarity computable
Embedding a trace segment converts its heterogeneous content into a point in high-dimensional space. LLM-generated embeddings act as feature extractors across language, role labels, tool names, and argument structure. Nearby points stand for semantically similar behavior, even when the text differs. Two traces in which an agent overwrites a test assertion to make it pass can therefore land near each other even when the files and assertion text differ.
The unit being embedded determines what that proximity reveals. A single-span embedding can localize a poisoned tool description, while a full-trace embedding can represent corruption that emerges over several steps. Neither view is sufficient on its own. The practical recommendation is to maintain parallel streams, using span embeddings for localization and trace embeddings for pattern-level clustering. Span windows, such as a reasoning step and the tool calls it produced, offer an intermediate resolution.
Benign traces provide a reference for interpreting the geometry. A detector trained on those traces learns where normal behavior sits, in a region often called the benign manifold. Points outside that region become anomaly candidates. Clustering then asks a different question, namely whether deviations recur in semantically related forms.
Segmenting and preparing traces for embedding
Segmentation and normalization shape whether a cluster leads to a real fix or just groups symptoms together. The first choice to make is where each segment begins and ends. Span boundaries preserve the natural unit of an agent action and support precise localization, but they can separate steps whose relationship exposes the failure. Plan-phase segmentation instead groups perception, planning, execution, or integration, supporting failure labels tied to those phases. Segmentation by interaction edge focuses on whether a failure originates at the model, tool, or retriever surface.
Normalization removes run-specific differences while preserving behavioral distinctions. Session IDs, timestamps, and user names can pull otherwise similar failures apart in embedding space. Role labels, tool names, argument schema shapes, and the natural-language content that matters should all stay. Argument shape is especially important for Tool-Hallucination failures, because sanitizing values must not erase the schema violation. A useful segment representation concatenates the role label, action type, tool name, argument schema rather than values, status, and natural-language content in a consistent order. That consistent order gives the embedding model inputs it can compare while keeping the evidence needed for fault attribution.
How to automatically group recurring AI agent failure patterns
HDBSCAN is the strongest fit among the clustering options here because it requires no preset number of failure types, handles variable-density groups, and leaves noise points unassigned. The number of recurring modes is unknown, and isolated anomalies need not belong to any recurring group. K-means is a poor fit because it requires a preset cluster count and forces every point into a group, potentially merging nearby but distinct failure modes.
Anomaly detectors can support this process without replacing clustering. Isolation Forest identifies individual anomalous points and can serve as a pre-clustering filter to distinguish rare one-off failures from recurring patterns. One-Class SVM learns a boundary around benign behavior, making it useful when successful traces are plentiful but failure examples are scarce. HDBSCAN addresses which points form recurring groups.
A useful cluster shares a deviation. Validation should establish whether members belong to the same failure family, such as planning, tool, retrieval, reasoning, or safety and policy. Re-running clustering on the next day's stream provides a stability check, with unstable membership signaling a possible segmentation or embedding artifact. A minimum member threshold also prevents a single outlier from becoming an operational pattern. Recurrence must be established before a group is treated as actionable.
Labeling clusters and connecting them to actionable failure categories
A geometric group has no remediation destination until its shared deviation is named. Automatic labeling can pass representative members, using the traces closest to the cluster centroid, to an LLM with a structured prompt. The prompt asks for the departure from expected behavior and its known failure category. Labels must describe behavior. This step converts similarity into a claim that can guide an engineering response.
The core taxonomy distinguishes planning errors, tool errors, retrieval errors, reasoning errors, and safety and policy violations. Planning includes wrong tool sequences, loops, missing steps, and plan-vs-execute divergence, while tool errors include wrong arguments, tool hallucination, and absent error handling. Retrieval covers wrong chunks, hallucinated sources, and role-switch tokens in retrieved content. Reasoning includes factual errors, ignored instructions, and hallucination on grounded context, while safety and policy includes PII leaks, jailbreak compliance, and outputs outside policy bounds. The v2.0 taxonomy adds categories such as Agentic Supply Chain Compromise and Inter-Agent Trust Escalation that may require extending this structure for multi-agent or MCP-connected deployments.
Ambiguous groups still need human judgment. Labels with low confidence or clusters that span two families should go into a review queue with representative traces already loaded. Once labeled, the centroid and member traces become an entry in a regression dataset against which later deployments can be checked for drift toward the same failure pattern.
Routing failure clusters to the right remediation surface
The failure category determines the fix surface. A planner-side failure routed to an output scanner leaves the planning defect untouched. Planning clusters call for tightening the planner prompt, enforcing the termination condition, or using a cycle detector. Their evaluation signal is the plan-vs-execute divergence score. That pairing connects the proposed change to the behavior the cluster exposed.
Tool clusters map to tool allowlists, argument schema guards, retry policies for non-OK responses, and MCP descriptor scans, with schema validation pass rate as an evaluation signal. Retrieval clusters map to the retriever rubric, chunker re-evaluation, and ingestion-time content controls. Their evaluation focuses on chunk relevance and source attribution accuracy. Reasoning clusters require a different intervention surface. They map to the generator rubric, LLM-as-judge checks on grounded-context faithfulness, and calibration set expansion.
Safety and policy clusters map to output scanners, refusal evaluations, and adversarial pushback sets. MCP/Plugin Abuse specifically calls for tool-description integrity checks at ingestion. The distinction keeps remediation close to the origin. Routing should send a Slack alert with the label, a representative trace, and the named fix surface through the workflow the team already uses. As labels accumulate, the routing map grows, and a recurring cluster without a destination signals the need for a new guardrail category.
The limits of off-manifold detection and what to do about them
A failure can stay close to benign behavior in embedding space. An attack that preserves normal role, provenance, dependency, and stability properties may avoid the anomaly signal even while redirecting the agent. Inherent failures pose the same problem. Hallucination on grounded context or reasoning built from steps that look plausible can have the same structure as successful execution.
An injected instruction can preserve a normal-looking workflow while changing the agent's terminal goal. The taxonomy describes this as Goal Hijacking without requiring full compromise of the underlying agent. A detector looking only for departure from normal trace structure can miss the redirection. Some harmful behavior has no useful geometric separation, which is a stronger objection to clustering than the noise it sometimes produces.
The appropriate response is a layered monitoring architecture. Embedding-based clustering finds recurring off-manifold patterns, while content-aware checks use LLM-as-judge against agent instructions, policy evaluations, and output scanners to assess semantic failures. Instruction-aware auditing compares what the agent was supposed to do with what it actually did, covering residual gaps. Regression suites built from clusters have the same blind spots as the detector and can miss failures that show up only in live interaction. Continuous production feedback and complementary checks make clustering useful as one layer of a monitoring architecture.
Building a continuous failure-pattern pipeline from trace ingestion to regression gates
The pipeline begins by ingesting every production trace, including runs that appear unremarkable. Filtering at ingestion would discard the silent failures the system is meant to discover. Compatibility reduces the cost of this coverage. The pipeline should accept standard telemetry spans and framework-native trace objects in their existing formats. Segmentation and normalization then apply the chosen span-level, phase-level, or combined resolution before embedding.
The embedding store must be versioned so changes caused by an embedding model update can be distinguished from behavioral drift. Incremental clustering compares new embeddings with the existing cluster library. Points that join an existing group update its centroid, and a new group triggers an alert when it reaches the minimum member threshold. High-confidence groups proceed through automatic labeling. Groups that are hard to label go to human review before routing sends a Slack alert with the failure category, representative trace, and named fix surface.
Labeled cluster members then become regression test cases, and each deployment is checked for how close it is to known failure clusters before promotion. New tool integrations, user behaviors, and attack surfaces keep bringing in patterns that a static ruleset or frozen evaluation suite cannot foresee. The pipeline's value therefore lies beyond its first useful cluster. Its growing library of labeled failures becomes institutional memory, making each subsequent deployment incrementally safer.
Sources
- Updating the taxonomy of failure modes in agentic AI systems: What a year of red teaming taught us
- Silent Failure in LLM Agent Systems: The Entropy Principle and the Inevitable Disorder of Autonomous Agents
- Model or Harness? An Interaction-Centric Taxonomy for Localizing Agent Failures
- Skynet: Workflow-Level Anomaly Detection for Agentic AI via Semantic and Structural Modeling
- APT-LLM: Embedding-Based Anomaly Detection of Cyber ...


