Skip to content

fix(metrics): keep metrics per invocation across awaits and child tasks - #1369

Merged
hjgraca merged 6 commits into
developfrom
fix/metrics-async-context
Nov 25, 2026
Merged

hjgraca merged 6 commits into
developfrom
fix/metrics-async-context

Conversation

@hjgraca

@hjgraca hjgraca commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: closes #1368

Summary

Changes

Metrics kept one MetricsContext per thread (ConcurrentDictionary<int, MetricsContext> keyed by Environment.CurrentManagedThreadId). An async invocation isn't tied to a thread, so its metrics were split across thread contexts and Flush only saw the one for the thread it ran on. This PR keys the context to the invocation instead.

 MetricsAspect.Before / UseMetrics() / WithMetrics()
+  Metrics.BeginInvocationContext()  # new context in AsyncLocal; continuations and child tasks inherit it
 <handler / request>                # AddMetric/AddDimension/AddMetadata -> that context
 MetricsAspect.Exit                 # (ASP.NET Core: no flush, the app calls Flush)
   Flush()
+  Metrics.EndInvocationContext()    # unregister it; nothing can write to it or flush it again
 Metrics.CurrentContext
-  _threadContexts.GetOrAdd(CurrentManagedThreadId, create)
+  nearest live invocation context in AsyncLocal<ContextScope>
+  ?? (AWS_LAMBDA_MAX_CONCURRENCY > 1
+        ? new context in the current async flow   # isolation between concurrent invocations (#1080)
+        : one process-wide fallback context)      # manual usage, one invocation at a time

How it works:

  • Invocation contexts (AsyncLocal<ContextScope>). The [Metrics] aspect, the UseMetrics() middleware and the WithMetrics() endpoint filter start a context before the handler/request runs and end it afterwards (in a finally for ASP.NET Core). The context flows across await, whatever thread resumes, and into Task.Run, Task.WhenAll, Parallel.ForEachAsync and new Thread. Concurrent invocations run in separate flows, so they stay isolated. The middleware and filter don't flush; applications still call Flush.

  • Nesting. A nested [Metrics] method, or WithMetrics() inside UseMetrics(), gets its own context with a parent link. When the inner one ends, the outer one is used again. AspectInjector weaves Before into the async stub, which runs in the caller's flow, and After just before SetResult. That's why contexts are chained and resolved by liveness instead of being restored on exit. The chain is capped (16), so it can't grow when invocations keep throwing (After doesn't run on exceptions).

  • Without an invocation context (manual usage). The behaviour depends on AWS_LAMBDA_MAX_CONCURRENCY, which is read on each lookup:

    • Unset, empty, unparsable or <= 1 (the default): one process-wide fallback context. This restores the pre-3.1 behaviour, so metrics first added inside an awaited helper are seen by the caller's Flush.
    • > 1: a context in the current async flow, created lazily, which keeps feat(metrics): thread safety with concurrent collections and isolation for metrics #1080's isolation for concurrent invocations. The caveat (first metrics call inside an awaited async method isn't visible to the caller) is documented.

    [Metrics] invocations and ASP.NET Core requests always get their own context and never use the fallback.

  • Registry of live contexts. A ConditionalWeakTable<MetricsContext, object> replaces _threadContexts for the code that updates every context (SetDefaultDimensions, ClearDefaultDimensions). It also decides whether a context is live: EndInvocationContext and ResetForTest remove entries, which kills that context in every flow still holding it. The fallback is registered like any other context and reset by ResetForTest. Every Flush clears it, as before. Keys are weak, so flow-local contexts that are never ended are collected with their flow. The registry can't grow without bound.

  • Configuration doesn't create a context. SetNamespace, SetService, SetDefaultDimensions, Options and Flush only touch an existing context plus the shared state.

  • Thread safety. An invocation's context (and the fallback) is shared by its child tasks, so compound operations hold a per-context lock (SyncRoot): overflow check + overflow flush + add, and serialize + clear in FlushContext. A concurrent add can't hit the 100-metric limit between the check and the add, or be dropped between serialize and clear.

No public API changes. Internal: ClearCurrentThreadContext (no callers) is now ClearCurrentContext, and ResetForTest works as before. The new code uses no reflection (AsyncLocal, ConditionalWeakTable, Environment.GetEnvironmentVariable), and the Release build has no IL trim/AOT warnings. Metrics.AspNetCore only calls the new internal Metrics methods (InternalsVisibleTo) and references no Common types.

User experience

Before (develop): in an async handler, metrics added before an await were lost whenever the continuation resumed on another thread. They also stayed in that thread's context, where a later invocation on the same thread flushed them as its own. Metrics from Task.Run children were only flushed when the flush happened to run on one of their threads. This made WhenMetricsAsyncRaceConditionItemSameKeyExists_ValidateLock flaky in CI.

After: everything an invocation adds (before or after await, from child tasks, from nested [Metrics] methods) is flushed with that invocation. Nothing leaks into another invocation, even when the previous one threw. ASP.NET Core requests behave the same with UseMetrics()/WithMetrics().

Behaviour users might notice:

  • Metrics that were only flushed "by luck" (child tasks, before an await) now always show up, so some functions will emit more data points than before.
  • Leaked metrics stop appearing in another invocation's output. That includes metrics from an invocation that threw before [Metrics] could flush them.
  • UseMetrics()/WithMetrics() now scope metrics to the request (or endpoint). Metrics a request adds but never flushes are dropped when it ends, instead of being picked up by a later request. With both, the endpoint's metrics are separate from metrics the request adds outside the endpoint (for example in a later middleware).
  • Manual usage with one invocation at a time (no [Metrics], no ASP.NET Core scoping) uses a single shared context again, as before 3.1. Metrics added outside any invocation context, for example in a constructor, go there and are flushed by the next manual Flush made outside an invocation context. A [Metrics] invocation only flushes its own context, so it no longer picks them up by chance.
  • Manual usage with AWS_LAMBDA_MAX_CONCURRENCY > 1: make the first metrics call in the method that calls Flush, not inside an async method it awaits (documented in docs/core/metrics.md). Before this PR, that case only worked when the code stayed on one thread.

Evidence

New deterministic tests. Each one forces the thread switch it depends on (an awaitable that resumes on a brand-new thread, or a dedicated thread that two invocations share), so none rely on luck. The red results are from develop or from the PR's previous revision. All pass now on net8.0 and net10.0.

Test Before Now
MetricAddedBeforeAwait_IsFlushed_WhenHandlerResumesOnAnotherThread ["AfterAwait"] (BeforeAwait lost) pass
MetricsFromChildTasks_AreAllFlushed_IncludingTheSameKeyFromManyTasks (100 same-key + 20 distinct + new Thread) no blob at all pass
ConcurrentChildTasks_OverflowingMaxMetrics_FlushEveryMetricExactlyOnce (8 tasks x 50) [] pass
ConcurrentInvocations_OnTheSameThread_DoNotShareMetricsDimensionsOrMetadata A's blob has B_metric pass
ConcurrentInvocations_WithoutAttribute_... (AWS_LAMBDA_MAX_CONCURRENCY=4) A's blob has B_metric pass
NextInvocation_OnTheThreadAPreviousOneUsed_... 1 blob (A+B) instead of 2 pass
NextInvocation_AfterAnAsyncInvocationThrew_... / ..._AfterASyncInvocationThrew_... ["FromB", "FromFailed"] pass
NestedAsyncMetricsMethod_... OuterBefore lost pass
ManualFlushAfterAwait_IncludesMetricsAddedBeforeTheAwait ["AfterAwait"] pass
ManualFlush_WithSingleConcurrency_SeesMetricFirstAddedInAwaitedHelperOnAnotherThread (unset, "", "1", unparsable) no blob (previous revision) pass
ManualFlush_WithSingleConcurrency_GetsDefaultDimensionUpdates_AndFlushClearsIt no blob (previous revision) pass
ManualFlush_WithSingleConcurrency_FlushesEveryMetricFromConcurrentChildTasksExactlyOnce no blob (previous revision) pass
ManualFlush_WithMultiConcurrency_DoesNotSeeMetricFirstAddedInAwaitedHelper (documented caveat) pass pass
MetricsInvocation_WithSingleConcurrency_GetsItsOwnContext_NotTheSharedOne pass pass
AspNetCore Endpoint_Flush_Sees_Metric_First_Added_In_Awaited_Helper_And_Requests_Do_Not_Share_Metrics (UseMetrics / WithMetrics / both) fail (previous revision) pass
AspNetCore When_Middleware_And_Filter_Are_Both_Used_The_Filter_Context_Ends_And_The_Request_Context_Is_Still_Used fail (previous revision) pass
AspNetCore When_UseMetrics_And_Endpoint_Resumes_On_Another_Thread_... fail (develop) pass

The AspNetCore request-scope tests run with AWS_LAMBDA_MAX_CONCURRENCY=4, so the fallback can't make them pass on its own. The Metrics tests in ConcurrencyTests simulate concurrent invocations, so they now run with AWS_LAMBDA_MAX_CONCURRENCY=4 and restore the previous value in Dispose.

Test runs (net8.0 and net10.0 each, rebased on e2c6166):

  • dotnet test libraries/tests/AWS.Lambda.Powertools.Metrics.Tests: 116/116 passed
  • dotnet test libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests: 22/22 passed (includes fix(metrics): skip ColdStart under provisioned concurrency in Metrics.AspNetCore #1365's provisioned-concurrency tests)
  • dotnet test libraries/tests/AWS.Lambda.Powertools.ConcurrencyTests: 526/526 passed
  • ValidateLock plus all AsyncContextTests (19 tests), 30 runs with --filter on net10.0: 30/30 passed
  • dotnet restore && dotnet build --configuration Release --no-restore from libraries/: succeeded, 0 errors, no IL trim/AOT warnings in Metrics

Merge Danger

Door: two-way. The change is internal to AWS.Lambda.Powertools.Metrics and Metrics.AspNetCore, and reverts cleanly. No public API or output format changes.

Blast Radius: Metrics

Every Metrics user goes through the new context lookup. The risk is in what gets flushed per invocation, as listed under "Behaviour users might notice". Metrics.AspNetCore now depends on new internal Metrics methods, so the two packages must be released together (they already are). Logging, Tracing, the other utilities and Common aren't touched.

Checklist

Please leave checklist items unchecked if they do not apply to your change.

Is this a breaking change?

RFC issue number:

Checklist:

  • Migration process documented
  • Implement warnings (if it can live side by side)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

@hjgraca hjgraca added bug Unexpected, reproducible and unintended software behaviour area/metrics Core metrics utility labels Nov 25, 2026
@boring-cyborg boring-cyborg Bot added documentation Improvements or additions to documentation tests labels Nov 25, 2026
@powertools-for-aws-oss-automation powertools-for-aws-oss-automation Bot added the size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. label Nov 25, 2026
…t invocations

Deterministic tests for #1368: each forces the thread switch it depends on.
Also covers an ASP.NET Core endpoint that resumes on another thread before flushing, and updates the concurrency test comments.
UseMetrics() and WithMetrics() begin an invocation context before next() and end it afterwards, so metrics first added in an awaited service method are seen by the endpoint's Flush.
Without an invocation context and with AWS_LAMBDA_MAX_CONCURRENCY unset or <= 1, use one process-wide fallback context, so metrics first added in an awaited helper are seen by the caller's Flush. With AWS_LAMBDA_MAX_CONCURRENCY > 1 keep flow-local contexts for isolation.
@hjgraca
hjgraca force-pushed the fix/metrics-async-context branch from d284170 to 4336bf6 Compare November 25, 2026 14:53
@powertools-for-aws-oss-automation powertools-for-aws-oss-automation Bot added size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. and removed size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Nov 25, 2026
@sonarqubecloud

Copy link
Copy Markdown

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.17989% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.29%. Comparing base (e2c6166) to head (4336bf6).

Files with missing lines Patch % Lines
...aries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs 93.25% 9 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1369      +/-   ##
===========================================
+ Coverage    80.16%   80.29%   +0.13%     
===========================================
  Files          303      303              
  Lines        12850    12962     +112     
  Branches      1530     1551      +21     
===========================================
+ Hits         10301    10408     +107     
- Misses        2094     2098       +4     
- Partials       455      456       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@hjgraca
hjgraca merged commit 57c40dc into develop Nov 25, 2026
12 checks passed
@hjgraca
hjgraca deleted the fix/metrics-async-context branch November 25, 2026 15:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/metrics Core metrics utility area/metrics-aspnetcore bug Unexpected, reproducible and unintended software behaviour documentation Improvements or additions to documentation size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Metrics lost in async handlers when the invocation resumes on a different thread

1 participant