cd /news/artificial-intelligence/sentry-s-span-hierarchy-exposed-a-si… Β· home β€Ί topics β€Ί artificial-intelligence β€Ί article
[ARTICLE Β· art-71526] src=dev.to β†— pub= topic=artificial-intelligence verified=true sentiment=Β· neutral

Sentry's Span Hierarchy Exposed a Silent Retry in My 5-Agent Pipeline. One Agent Took 22.6s, the Others Took 5.

A developer built an AWS Security Posture Agent using five specialist AI agents on CrewAI with Amazon Bedrock Nova Pro. One agent took 22.6 seconds while others averaged 5-10 seconds; Sentry's trace waterfall revealed the SecurityScanner agent was overwhelmed by a 27KB JSON payload from the IAMAnalyzer tool, causing CrewAI's retry logic to fire. The fix limited IAM role analysis to the top 20 most active roles, reducing the payload and normalizing execution times.

read7 min views2 publishedJul 24, 2026

This is a submission for DEV's Summer Bug Smash: Clear the Lineup powered by Sentry.

I built an AWS Security Posture Agent: five specialist AI agents that scan your AWS account for security misconfigurations, map findings to CIS benchmarks, score risk, and generate copy-paste fix commands.

The agents run sequentially on CrewAI with Amazon Bedrock Nova Pro as the LLM:

1. ResourceDiscovery    β†’ inventories EC2, S3, Lambda, IAM, SGs, API GW, DynamoDB
2. SecurityScanner      β†’ finds open ports, public buckets, admin roles, insecure configs
3. ComplianceChecker    β†’ maps to CIS AWS Foundations Benchmark
4. RiskScorer           β†’ severity Γ— blast radius Γ— exploitability
5. RemediationPlanner   β†’ generates AWS CLI fix commands

Each agent has custom boto3 tools that make real AWS API calls against a live account with 90 IAM roles, 14 S3 buckets, 9 security groups, and 7 Lambda functions. Not test data. Real findings.

Five AI agents scan your AWS account. Find misconfigurations. Score risk. Get fix commands.

Most AWS accounts accumulate security debt silently. Open SSH ports from testing. S3 buckets without encryption. IAM roles with full admin access that nobody remembers creating. Manual audits miss things. AWS Config rules cost money. SecurityHub is noisy.

This agent scans your account in 60 seconds, finds real issues, maps them to CIS benchmarks, scores risk, and gives you the exact AWS CLI command to fix each one.

On a real AWS account (90 IAM roles, 14 S3 buckets, 9 security groups, 7 Lambda functions):

97 security findings
β”œβ”€β”€ CRITICAL: open SSH/RDP from 0.0.0.0/0, IAM users without MFA
β”œβ”€β”€ HIGH:     admin roles, unencrypted EBS, missing public access blocks
β”œβ”€β”€ MEDIUM:   deprecated Lambda runtimes, missing versioning, stale SGs
└──

…Here's the full scan running against my AWS account. The scan portion is sped up 4x, results walkthrough is at normal speed:

My first instinct was to blame Bedrock latency. Every time something is slow you blame the LLM, right?

The SecurityScanner agent was taking 22.6 seconds while every other agent averaged 5-10 seconds. Without visibility into what was happening inside each agent's execution, I would have added time.time()

calls and guessed.

Sentry's trace waterfall told a different story. The real problem wasn't Python execution time or network latency. It was the LLM getting a context payload it couldn't process cleanly on the first attempt.

The root cause: my IAMAnalyzer

tool was fetching all 90 IAM roles from the account (59 after filtering service-linked roles), serializing them into a 27KB JSON blob, and handing that entire payload to the LLM as tool output. The context window got overwhelmed. CrewAI's internal retry logic kicked in, burning tokens on a second attempt with even more context.

One tool. Wrong default. The entire pipeline suffered.

PR with the fix:

The IAMAnalyzer tool was fetching every single role in the account (90 of them, 59 after filtering service-linked ones) and dumping the full details into a single JSON blob. That blob hit 26,980 characters. The LLM choked on it, CrewAI retried the task, and the SecurityScanner agent ended up taking 22.6s while every other agent finished in 5-10s.

Added Sentry spans to each agent and tool. The trace waterfall made it obvious: SecurityScanner was twice as wide as everything else. Drilled into the tool spans and saw result_length_chars: 26980

on iam_analyzer

vs ~4000 on the other tools.

7x output disproportion. That was the problem.

Three things in iam_analyzer.py

:

RoleLastUsed

date, only analyze the top 20 most active ones. The rest are stale roles nobody has touched in months.The core change lives in src/security_posture/tools/iam_analyzer.py

. Here's the before and after:

Before (the bug):

roles = iam.list_roles(MaxItems=100)
role_details = []

for role in roles["Roles"]:
    role_name = role["RoleName"]
    if role.get("Path", "").startswith("/aws-service-role/"):
        continue
    attached = iam.list_attached_role_policies(RoleName=role_name)

This produces 26,980 characters of JSON for an account with 90 roles. The LLM chokes on it.

After (the fix):

all_roles = []
paginator = iam.get_paginator("list_roles")
for page in paginator.paginate():
    all_roles.extend(page["Roles"])

auditable_roles = [
    r for r in all_roles
    if not r.get("Path", "").startswith("/aws-service-role/")
]

auditable_roles.sort(key=_last_used_sort_key, reverse=True)

roles_to_analyze = auditable_roles[:max_roles]

Plus a token budget guard at the end:

if len(output) > 4000:
    result["role_summary"] = [
        {"role_name": r["role_name"], "policies": r.get("attached_policies", [])}
        for r in role_details
    ]
    result["note"] = "Role details truncated to stay within token budget"
    output = json.dumps(result, indent=2, default=str)

Three changes. Pagination, relevance sorting, and a safety valve. The SecurityScanner stopped retrying.

Results first:

Metric Before After Improvement
IAM tool output 26,980 chars 15,532 chars 42% smaller
SecurityScanner time 22.6s 17.8s 21% faster
IAM API calls 59 20 66% fewer
Total pipeline 62.0s 57.7s 7% faster
Security findings 97 97 No coverage loss

The 21% improvement on the SecurityScanner came from the LLM completing analysis in a single pass instead of retrying.

How I found it:

The fix itself is simple. The interesting part is how Sentry pointed me straight to it.

Without the trace waterfall, all I would have seen is "pipeline takes 62 seconds." The trace said otherwise:

gen_ai.invoke_agent

spangen_ai.execute_tool

spaniam_analyzer

tool span showed a result_length_chars

of 26,980security_group_analyzer

at 4,200 chars and s3_config_checker

at 3,800 charsThe disproportion was the clue. If the tool output is 7x larger than its siblings, reduce it.

I used Sentry's AI Agent Monitoring to instrument a multi-agent CrewAI pipeline from scratch. This isn't a web app or API. It's five autonomous AI agents making LLM calls and executing custom tools. Standard APM wouldn't help here.

Every pipeline run creates a Sentry transaction with this span hierarchy:

Transaction: "Security Posture Scan" (57s)
β”œβ”€β”€ gen_ai.invoke_agent: ResourceDiscovery
β”‚   └── gen_ai.execute_tool: aws_resource_scanner
β”œβ”€β”€ gen_ai.invoke_agent: SecurityScanner
β”‚   β”œβ”€β”€ gen_ai.execute_tool: security_group_analyzer
β”‚   β”œβ”€β”€ gen_ai.execute_tool: s3_config_checker
β”‚   β”œβ”€β”€ gen_ai.execute_tool: iam_analyzer
β”‚   β”œβ”€β”€ gen_ai.execute_tool: ec2_security_checker
β”‚   └── gen_ai.execute_tool: lambda_security_checker
β”œβ”€β”€ gen_ai.invoke_agent: ComplianceChecker
β”œβ”€β”€ gen_ai.invoke_agent: RiskScorer
└── gen_ai.invoke_agent: RemediationPlanner

For each agent (in main.py

):

with start_span(
    op="gen_ai.invoke_agent",
    name=f"invoke_agent {agent_name}",
) as agent_span:
    agent_span.set_data("gen_ai.operation.name", "invoke_agent")
    agent_span.set_data("gen_ai.agent.name", agent_name)
    agent_span.set_data("gen_ai.request.model", "amazon.nova-pro-v1:0")
    agent_span.set_data("gen_ai.pipeline.name", "security-posture-scan")

    task_output = task_obj.execute_sync(
        agent=task_obj.agent,
        context=context,
        tools=task_obj.agent.tools,
    )

    agent_span.set_data("duration_seconds", round(elapsed, 2))
    agent_span.set_data("output_length_chars", len(str(task_output)))

For each tool (decorator in monitoring.py

):

def trace_tool(tool_name: str):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with start_span(
                op="gen_ai.execute_tool",
                name=f"execute_tool {tool_name}",
            ) as span:
                span.set_data("gen_ai.tool.name", tool_name)
                result = func(*args, **kwargs)
                span.set_data("result_length_chars", len(result))
                try:
                    data = json.loads(result)
                    if "findings_count" in data:
                        span.set_data("findings_count", data["findings_count"])
                except (json.JSONDecodeError, KeyError):
                    pass
                return result
        return wrapper
    return decorator

The trace waterfall made the bottleneck visually obvious. The SecurityScanner span was nearly twice the width of any other agent, 22.6 seconds while others averaged 5-10s.

Inside it, the iam_analyzer

tool span showed result_length_chars: 26980

while s3_config_checker

showed 3,800 and security_group_analyzer

showed 4,200. The granularity goes down to individual boto3 calls. Every GetPublicAccessBlock

, ListRoles

, and ListAttachedRolePolicies

shows up as its own span.

Before the fix (SecurityScanner dominates the trace at 22.6s):

After the fix (all agents proportional, no single bottleneck):

The iam_analyzer

output dropped from 26,980 chars to 15,532, and the SecurityScanner stopped triggering retry logic.

Feature How I Used It
Distributed Tracing
Full pipeline trace from start to final report
AI Agent Monitoring
gen_ai.invoke_agent spans for all 5 agents
Tool Execution Tracing
gen_ai.execute_tool spans for all 5 boto3 tools
Custom Span Data
Token counts, output sizes, duration, finding counts
Error Monitoring
Exception capture with sentry_sdk.capture_exception()
Breadcrumbs
Agent completion events via task callbacks
Transaction Metadata
Model name, pipeline config, agent count

Standard logging tells you an agent "finished." It doesn't tell you which tool inside which agent returned a 27KB payload that triggered a retry you never asked for.

With five agents each making their own LLM calls and tool executions, you need span-level visibility. Sentry's gen_ai.invoke_agent

and gen_ai.execute_tool

conventions gave me exactly that. I could see the problem in the trace waterfall before I even looked at the code.

That's the difference between "add some logging" and actual AI observability.

If you're running multi-agent pipelines, what's your observability setup? Curious if anyone else has hit similar tool-output-size problems with CrewAI or LangGraph.

The agent found 97 real security findings in my AWS account. The fix is in production.

── more in #artificial-intelligence 4 stories Β· sorted by recency
── more on @sentry 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain β€” perfect for shipping the agent you just read about.

$git push zahid main
β†’ Live at https://your-agent.zahid.host βœ“
Get free account β†’ Pricing
from €0/mo Β· no card required
LIVE [news/sentry-s-span-hierar…] indexed:0 read:7min 2026-07-24 Β· β€”