This post is part of the series 'Debugging .NET with an AI agent'. Be sure to check out the rest of the blog posts of the series!
The three Aspire posts of this series read telemetry that was already there. The first one counted the spans of a slow request, the second one needed the logs that went with them, the third one needed the metrics of the process. The answer was in the data every time.
This time it is not. The slow endpoint runs one query, the query takes 2 ms, and the request takes 371 ms. Its trace has three spans, and none of them covers those 371 ms.
That is not a gap in Aspire. The built-in instrumentation covers what crosses the process boundary: the incoming request, the outgoing HTTP calls, the database commands. What the code does between them is invisible, and a lot of code does something between them.
So the agent has to write the missing spans before it can answer the question. That is a change to the application, decided before the root cause is known, which is exactly what rule 6 of the skill forbids. This post is about the exception, about the spans an agent produces when it is allowed to make it, and about the four ways the result misleads the model that wrote it.
The sample contains the application and the skill. Every output below comes from it, with the same versions as in the previous posts.
#The application
C#
var builder = DistributedApplication.CreateBuilder(args);
var database = builder.AddPostgres("postgres")
.AddDatabase("catalogdb");
var catalog = builder.AddProject<Projects.CatalogApi>("catalog-api")
.WithReference(database)
.WaitFor(database)
.WithHttpHealthCheck("/health");
builder.AddProject<Projects.LoadGenerator>("load-generator")
.WithReference(catalog)
.WaitFor(catalog);
builder.Build().Run();
catalog-api loads the whole catalog, 150,000 products, in memory at startup, and serves two endpoints from that snapshot:
GET /search?q= searches the products by name and by description. It reads the catalog revision from the database first, to know whether its snapshot is still current.GET /products/{id} returns one product from a dictionary.
The load generator runs 4 search loops, like a search box, and 2 product loops, like the product pages. Under this load a search takes about 370 ms, and a product page takes 0.1 ms. Both read the same snapshot, in the same process.
#Ask the question
GET /search on catalog-api takes about 400 ms under load, while the only query it runs takes less than a
millisecond and the trace shows nothing else. The application is running under Aspire. Find out where the
time goes.
#Step 1: what the existing telemetry says
The agent listed the traces of the resource, and got the comparison rule 3 asks for in the same output (URLs removed):
Shell
aspire otel traces catalog-api --apphost AppHost/AppHost.csproj -n 60
│ 14:43:42.151 │ catalog-api: GET /search 1875d7d │ 2 │ 0.37s │ OK │
│ 14:43:42.151 │ catalog-api: GET /search 0639af2 │ 2 │ 0.37s │ OK │
│ 14:43:42.159 │ catalog-api: GET /search 2b81662 │ 2 │ 0.37s │ OK │
│ 14:43:42.488 │ catalog-api: GET /products/{id:int} e7cc694│ 1 │ 0.03ms │ OK │
│ 14:43:42.522 │ catalog-api: postgresql d6a2c58 │ 1 │ 0.89ms │ OK │
Then it opened one of the slow traces:
kind Client name GET source load-generator durationMs 371 timestamp 18:43:42.151295Z
kind Server name GET /search source catalog-api durationMs 371 timestamp 18:43:42.151452Z
kind Client name postgresql source catalog-api durationMs 2 timestamp 18:43:42.151483Z
db.query.text "SELECT revision FROM catalog_revision WHERE id = 1"
The agent: "The only query is a tiny revision check, and it starts 31 microseconds after the server span. So the 368 ms gap is NOT waiting for a pooled connection (that would sit before the first DB span) - it is inside the handler, after the revision query."
That distinction is what the previous post put in the skill. A gap before the first database span is a connection pool queue. A gap after it is something else, and the trace has nothing more to say about it: three spans, one of them 2 ms, and 368 ms that belong to no span at all.
#Step 2: is the process working, or waiting?
A gap is not evidence of computation. A lock, a Task.Delay, or an HTTP call through a client that nobody instrumented produce the same empty space. The skill requires the difference to be settled before the code is touched, and the metrics of the process settle it:
Shell
dotnet-counters collect -n CatalogApi --counters Microsoft.AspNetCore.Hosting,System.Runtime \
--format json --refresh-interval 2 --duration 00:00:00:20 -o counters-before.json
dotnet.process.cpu.count ({cpu}) 15
dotnet.process.cpu.time (s / 2 sec) [cpu.mode=user] 8.417674999999917
dotnet.gc.heap.total_allocated (By / 2 sec) 7909006144
dotnet.thread_pool.queue.length ({work_item} / 2 sec) 0
http.route=/search,Percentile=50 0.361328125
http.route=/products/{id:int},Percentile=50 0.0000966787338256836
8.4 seconds of user CPU per 2-second interval, on 15 CPUs: 4 cores busy without interruption. 7.9 GB allocated per 2 seconds, about 4 GB/s. A thread pool queue that does not grow. The process is not waiting for anything, it is computing, and it allocates like code that builds strings in a loop.
The three conditions of the skill's new section hold: the gap is inside the handler, the process really works during it, and the code that runs there is one method. The agent read that method, found LINQ over an in-memory array, called the double enumeration on line 42 "a suspicion, not yet proof", and went to get the proof.
A CPU profiler would also produce it. dotnet-trace collect --profile cpu-sampling names the method that burns the samples, and it needs no code change. It answers a different question: it tells what the process does, not what a request does. It cannot say "the search costs 370 of the 371 ms of this request", it cannot be read per route under mixed load, and it is not there the next time somebody asks. Spans are worth their edit because they stay.
#Step 3: the spans the agent writes
Every line of the skill's Adding instrumentation section exists because a model gets it wrong without it. The result, after those rules:
C#
private static readonly ActivitySource Source = new("Catalog.Search");
private static readonly Meter Meter = new("Catalog.Search");
private static readonly Histogram<double> PhaseDuration = Meter.CreateHistogram<double>("catalog.search.phase.duration", "s");
public SearchResults Search(string query)
{
using var activity = Source.StartActivity("catalog.search");
var matchEvaluations = 0;
var scoreEvaluations = 0;
string[] terms;
using (StartPhase("tokenize"))
{
terms = Tokenize(query);
}
var matches = _products.Where(product =>
{
matchEvaluations++;
return Matches(product, terms);
});
SearchItem[] items;
using (StartPhase("rank"))
{
items = [.. matches
.OrderByDescending(product =>
{
scoreEvaluations++;
return Score(product, terms);
})
.Take(20)
.Select(product => new SearchItem(product.Id, product.Name))];
}
int total;
using (StartPhase("count"))
{
total = matches.Count();
}
activity?.SetTag("catalog.search.term_count", terms.Length);
activity?.SetTag("catalog.search.products", _products.Length);
activity?.SetTag("catalog.search.match_evaluations", matchEvaluations);
activity?.SetTag("catalog.search.score_evaluations", scoreEvaluations);
activity?.SetTag("catalog.search.matched", total);
activity?.SetTag("catalog.search.returned", items.Length);
return new SearchResults(total, items);
}
One span per phase, with a histogram sample per phase on the side:
C#
private readonly struct PhaseScope : IDisposable
{
private readonly Activity? _activity;
private readonly string _phase;
private readonly long _start;
public PhaseScope(string phase)
{
_phase = phase;
_activity = Source.StartActivity("catalog.search." + phase);
_start = Stopwatch.GetTimestamp();
}
public void Dispose()
{
PhaseDuration.Record(Stopwatch.GetElapsedTime(_start).TotalSeconds, new KeyValuePair<string, object?>("phase", _phase));
_activity?.Dispose();
}
}
And the registration, which is the line everything depends on:
C#
// The service defaults only register the assembly name as a source: the custom spans and metrics of the
// search need their own registration, or nothing is exported
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing.AddSource("Catalog.Search"))
.WithMetrics(metrics => metrics.AddMeter("Catalog.Search"));
Three things in this code are there because the skill says so, and are worth keeping in a skill of your own:
- The counters in the tags.
matchEvaluations and scoreEvaluations count how many times a lambda ran. A duration says a phase is slow; a count says how much work the phase did, which is what distinguishes slow code from too much code. - Spans around phases, never around items. The rule is in the skill with a reason, and the measurement is further down.
- No
q in the tags. The search terms are the user's.
#Step 4: what the new trace says
After aspire resource catalog-api rebuild, the same request has 6 spans instead of 3:
14:48:39.182 OK 1.01ms catalog-api: postgresql 559efe3
14:48:39.183 OK 0.37s catalog-api: catalog.search 4e5c158
14:48:39.183 OK 3μs catalog-api: catalog.search.tokenize 3092f32
14:48:39.183 OK 0.19s catalog-api: catalog.search.rank 5344e86
14:48:39.374 OK 0.18s catalog-api: catalog.search.count 9db79a5
With the tags of the parent span:
catalog.search kind=Internal durationMs=370
catalog.search.term_count 2
catalog.search.products 150000
catalog.search.match_evaluations 300000
catalog.search.score_evaluations 18750
catalog.search.matched 18750
catalog.search.returned 20
Three numbers end the investigation:
- 370 of the 371 ms are inside
catalog.search. The database and the framework are innocent. - The time is split in half between two phases: ranking 20 products costs 191 ms, and counting the matches costs 179 ms.
- 300,000 match evaluations for 150,000 products. The predicate runs exactly twice per product.
matches is a lazy IEnumerable. It is enumerated once to rank the top 20, and a second time by matches.Count(), which the original code hid inside the returned value:
C#
return new SearchResults(matches.Count(), items);
And what each of those 300,000 evaluations does is normalize both strings of a product, with string.Normalize(NormalizationForm.FormD) and a StringBuilder, to make "Crème fraîche BIO" match "creme fraiche bio". That is 600,000 normalizations of data that only changes when the snapshot is reloaded. It explains the 4 GB/s.
#The fix
Normalize once per product at load time, keeping the result next to the product in a private Entry record, and materialize the matches once:
C#
_products = [.. products];
// The normalized form of a product only changes when the snapshot is reloaded: compute it here,
// once per product, instead of on every request
_entries = [.. products.Select(product => new Entry(product, Normalize(product.Name), Normalize(product.Description)))];
C#
var matches = _products.Where(product => Matches(product, terms));
var items = matches
.OrderByDescending(product => Score(product, terms))
.Take(20)
.Select(product => new SearchItem(product.Id, product.Name))
.ToArray();
return new SearchResults(matches.Count(), items);
// Materialized: the scan must run once, not once per consumer of the enumerable
Entry[] matches;
using (StartPhase("match"))
{
matches = [.. _entries.Where(entry =>
{
matchEvaluations++;
return Matches(entry, terms);
})];
}
SearchItem[] items;
using (StartPhase("rank"))
{
items = [.. matches
.OrderByDescending(entry => Score(entry, terms))
.Take(20)
.Select(entry => new SearchItem(entry.Product.Id, entry.Product.Name))];
}
return new SearchResults(matches.Length, items);
The agent also deleted the tokenize span, which measured 3 µs and said nothing, and kept the phase spans and the tags. The skill asks for that cleanup: instrumentation added during an investigation is a draft, and the part of it that answers the question is the part worth shipping.
Before the rebuild it checked the responses of three of the load generator's queries, and compared them after: identical totals, identical top 20, identical order. Then it measured the same way it had measured the problem:
| Measurement | Before | After |
|---|
/search p50, http.server.request.duration | 0.361 s | 0.0125 s |
/search p99 | 0.368 s | 0.0188 s |
GET /search server span | 371 ms | 19 ms |
catalog.search span | 370 ms | 16 ms |
| Phases | rank 191 ms + count 179 ms | match 12 ms + rank 4 ms |
catalog.search.match_evaluations | 300,000 | 150,000 |
| User CPU per 2 s, 15 CPUs | ~8.2 s | ~1.1 s |
| Allocated per 2 s | ~7.8 GB | ~1.17 GB |
/products/{id} p50, untouched | 0.0000967 s | 0.000118 s |
29 times faster on the p50, with a seventh of the CPU and a sixth of the allocations. 31 tool calls, about ten minutes, most of it waiting for the load to run after each rebuild.
The match_evaluations tag is the reason to keep that instrumentation: 300,000 became 150,000, and the day somebody reintroduces a second enumeration, the number says so in every trace.
#The metric outlives the investigation
The histogram answers the question the spans cannot: what the phases look like over all the requests, not in the one trace somebody opened.
Shell
dotnet-counters collect -n CatalogApi --counters Catalog.Search,Microsoft.AspNetCore.Hosting,System.Runtime \
--format json --refresh-interval 2 --duration 00:00:00:20 -o phases.json
before after
phase=count,Percentile=50 0.1845703125 phase=match,Percentile=50 0.00787353515625
phase=rank,Percentile=50 0.1904296875 phase=rank,Percentile=50 0.002971649169921875
phase=tokenize,Percentile=50 0.0000024996697902679443
phase has three possible values, which is what makes it a usable tag. The same code with SetTag("query", query) on the histogram would create one time series per search ever made, in a process that never restarts.
#Instrumentation that lies
Four ways to get nothing, or worse than nothing, out of custom spans. The agent avoided the first two because the skill warned it, and I measured what they cost without the warning. It walked into the last two.
##The span that is never exported
ActivitySource.StartActivity returns null when nothing listens to the source, and a null activity records nothing. Nothing listens until the source is registered, and the Aspire service defaults register exactly one:
C#
.WithTracing(tracing => tracing
.AddSource(builder.Environment.ApplicationName)
ApplicationName is the name of the entry assembly, CatalogApi. An ActivitySource named CatalogApi therefore works out of the box, and every other name is dropped in silence. I removed the AddSource("Catalog.Search") line, kept the instrumented code as it was, and rebuilt:
133 search traces, all of them with 3 spans, span names: GET, GET /search, postgresql
median duration: 379 ms
The Activity objects are created, the tags are computed, the histogram is recorded, and the dashboard receives none of it. There is no warning and no error. A model that reads this trace concludes that the time is not in the code it just instrumented, which is the most expensive wrong answer available.
There is an asymmetry worth knowing here. dotnet-counters does not care about AddMeter: it attaches to the instruments of the process directly, so the same run still reports the histogram.
catalog.search.phase.duration (s) [phase=count,Percentile=50] 0.193359375
A metric can therefore be readable with dotnet-counters and absent from the dashboard. AddMeter is what puts it in the OTLP export; AddSource is what makes a span exist at all.
##One span per item
The obvious place for a span is the loop, and it is the one place it must not go. One line inside the predicate:
C#
var matches = _products.Where(product =>
{
using var span = Source.StartActivity("catalog.search.product");
matchEvaluations++;
return Matches(product, terms);
});
300,000 spans per request, about seven requests per second. What that does, measured with the same counter as everything else:
/search p50, no custom spans: 0.361 s
/search p50, phase spans: 0.372 s to 0.416 s
/search p50, one span per item: 0.554 s
The instrumentation added about 150 ms to a request that took 370, and it did much worse than slow the request down. The trace list stops being readable:
│ 15:00:02.663 │ catalog-api: catalog.search.product 69b89ee │ 28023 │ 2.53ms │ OK │
│ 15:00:02.813 │ catalog-api: catalog.search.product 9671851 │ 25357 │ 2.52ms │ OK │
│ 15:00:03.039 │ catalog-api: catalog.search.rank e718631 │ 14491 │ 0.3s │ OK │
And the trace itself loses the spans that mattered. Grouping the spans of one of those traces by name:
catalog.search.product 27803
GET 1
GET /search 1
27,803 of the 300,000 spans arrived, and catalog.search, the phase spans, and the postgresql span are not in the trace at all. The exporter drops spans when its queue is full, and the spans that end last, at the moment of maximum pressure, are the request-level ones. The instrumentation deleted its own evidence.
Counts belong in tags. A phase span with catalog.search.products = 150000 costs one span and says more than 150,000 spans.
##The newest traces are the in-flight ones
Right after the rebuild, the agent looked at the last traces and found no /search line at all:
│ 14:48:26.034 │ load-generator: GET 1088c85 │ 1 │ 0.38s │ OK │
│ 14:48:26.088 │ load-generator: GET 6dec74e │ 1 │ 0.48ms │ OK │
It "briefly suspected the rebuild had broken the app". It had not: a span reaches the dashboard when it ends, so the most recent traces are the requests still running, with only the spans that already completed. -n 300 showed the finished ones.
The same effect has a second form, which the agent got slightly wrong in passing: the catalog-api: postgresql entries with a single span, which it first read as "database work happening outside any request's trace context". They are not. Every one of them has a parentSpanId; what they are missing is the rest of their trace, either because it has not been exported yet or because the dashboard evicted it. The mistake is harmless here and dangerous in general: an orphan span looks exactly like work that lost its trace context, which is a real bug in other applications. parentSpanId tells the two apart, and that line is now in the skill.
##The process is not there yet
dotnet-counters collect immediately after aspire resource <name> rebuild:
There is no active process with the given name: CatalogApi
The resource restarts with a new pid, and dotnet-counters ps is how to find it. Cheap mistake, and the reason the skill already says to find the process by name rather than by the pid a tool reported earlier.
#Telemetry contains secrets, again
Every post of this sub-series ends here, and this one adds the interesting case: the secrets are the ones the agent writes itself.
url.query is already in every server span, with the value of q: the ASP.NET Core instrumentation records the query string as it received it. A custom catalog.search.query tag adds a second copy of the user's search, and the agent has no way to know your retention rules.- What an agent puts in a tag goes to the dashboard, to the OTLP exporter, and to whatever the collector forwards to.
terms.Length is a count; terms is data. - A tag on a metric is worse than a tag on a span: it creates one time series per distinct value, for the lifetime of the process. A query, a product id, or a duration as a tag is an unbounded set.
dotnet-counters reads any .NET process of the same user, and the Npgsql pool name in its output still carries the host, the port, the user name and the database.
#What the agent gets wrong, and how to fix it
It would not have instrumented at all. Rule 6 says never to modify the source before the telemetry supports a root cause. Taken literally, it makes this investigation impossible, and a model that follows rules literally stops at "the time is inside the handler".
Fix: the exception, written in the rule itself. Adding spans is how the evidence is obtained; changing behaviour still waits for the evidence. The three conditions above are what keep the exception from becoming "edit the code whenever you are stuck".
It instruments what is easy to instrument. A span per item, a span per call, a span per branch. Every one of them is a plausible measurement and a trace that cannot be read.
Fix: phases and counts, as a hard rule with the numbers above attached to it.
It trusts its own spans before checking they arrived. Every failure mode of a custom span, from the missing AddSource to a sampler that drops the parent, looks like "no time is spent here".
Fix: one line in the skill: the new spans must be in the trace before anything is read into them. A phase span that covers 370 of 371 ms also proves the instrumentation works, which is a second reason to start at the top.
It reports at the end. Rule 5 asks for a report every ~15 tool calls; this run went to 31 without one, and the rebuild cycles are exactly where a human would want to hear what the plan is.
Fix: unsolved. The rule is in the skill, and the agent said so itself in its report, which is not the same as obeying it.
Three investigations read the telemetry of an application. This one wrote it. The interesting part is not that an agent can add an ActivitySource — that is a small amount of code, and it is in the training data a thousand times over. It is that instrumentation is a measurement device, and that a model left to build its own will happily build one that changes what it measures, drops what it records, or records what it should never see. The skill is how those failures stop being surprises, and every line of it was written after one of them.
#Additional resources
Do you have a question or a suggestion about this post? Contact me!