Repository navigation
fix(metrics): keep metrics per invocation across awaits and child tasks - #1369
Merged
Merged
Conversation
…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.
…NET Core request scopes
hjgraca
force-pushed
the
fix/metrics-async-context
branch
from
November 25, 2026 14:53
d284170 to
4336bf6
Compare
|
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Issue number: closes #1368
Summary
Changes
Metricskept oneMetricsContextper thread (ConcurrentDictionary<int, MetricsContext>keyed byEnvironment.CurrentManagedThreadId). An async invocation isn't tied to a thread, so its metrics were split across thread contexts andFlushonly saw the one for the thread it ran on. This PR keys the context to the invocation instead.How it works:
Invocation contexts (
AsyncLocal<ContextScope>). The[Metrics]aspect, theUseMetrics()middleware and theWithMetrics()endpoint filter start a context before the handler/request runs and end it afterwards (in afinallyfor ASP.NET Core). The context flows acrossawait, whatever thread resumes, and intoTask.Run,Task.WhenAll,Parallel.ForEachAsyncandnew Thread. Concurrent invocations run in separate flows, so they stay isolated. The middleware and filter don't flush; applications still callFlush.Nesting. A nested
[Metrics]method, orWithMetrics()insideUseMetrics(), gets its own context with a parent link. When the inner one ends, the outer one is used again. AspectInjector weavesBeforeinto the async stub, which runs in the caller's flow, andAfterjust beforeSetResult. 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 (Afterdoesn't run on exceptions).Without an invocation context (manual usage). The behaviour depends on
AWS_LAMBDA_MAX_CONCURRENCY, which is read on each lookup:<= 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'sFlush.> 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 awaitedasyncmethod 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_threadContextsfor the code that updates every context (SetDefaultDimensions,ClearDefaultDimensions). It also decides whether a context is live:EndInvocationContextandResetForTestremove entries, which kills that context in every flow still holding it. The fallback is registered like any other context and reset byResetForTest. EveryFlushclears 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,OptionsandFlushonly 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 inFlushContext. 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 nowClearCurrentContext, andResetForTestworks as before. The new code uses no reflection (AsyncLocal,ConditionalWeakTable,Environment.GetEnvironmentVariable), and the Release build has no IL trim/AOT warnings.Metrics.AspNetCoreonly calls the new internalMetricsmethods (InternalsVisibleTo) and references no Common types.User experience
Before (develop): in an async handler, metrics added before an
awaitwere 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 fromTask.Runchildren were only flushed when the flush happened to run on one of their threads. This madeWhenMetricsAsyncRaceConditionItemSameKeyExists_ValidateLockflaky 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 withUseMetrics()/WithMetrics().Behaviour users might notice:
await) now always show up, so some functions will emit more data points than 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).[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 manualFlushmade outside an invocation context. A[Metrics]invocation only flushes its own context, so it no longer picks them up by chance.AWS_LAMBDA_MAX_CONCURRENCY > 1: make the first metrics call in the method that callsFlush, not inside anasyncmethod it awaits (documented indocs/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.
MetricAddedBeforeAwait_IsFlushed_WhenHandlerResumesOnAnotherThread["AfterAwait"](BeforeAwait lost)MetricsFromChildTasks_AreAllFlushed_IncludingTheSameKeyFromManyTasks(100 same-key + 20 distinct +new Thread)ConcurrentChildTasks_OverflowingMaxMetrics_FlushEveryMetricExactlyOnce(8 tasks x 50)[]ConcurrentInvocations_OnTheSameThread_DoNotShareMetricsDimensionsOrMetadataB_metricConcurrentInvocations_WithoutAttribute_...(AWS_LAMBDA_MAX_CONCURRENCY=4)B_metricNextInvocation_OnTheThreadAPreviousOneUsed_...NextInvocation_AfterAnAsyncInvocationThrew_.../..._AfterASyncInvocationThrew_...["FromB", "FromFailed"]NestedAsyncMetricsMethod_...ManualFlushAfterAwait_IncludesMetricsAddedBeforeTheAwait["AfterAwait"]ManualFlush_WithSingleConcurrency_SeesMetricFirstAddedInAwaitedHelperOnAnotherThread(unset,"","1", unparsable)ManualFlush_WithSingleConcurrency_GetsDefaultDimensionUpdates_AndFlushClearsItManualFlush_WithSingleConcurrency_FlushesEveryMetricFromConcurrentChildTasksExactlyOnceManualFlush_WithMultiConcurrency_DoesNotSeeMetricFirstAddedInAwaitedHelper(documented caveat)MetricsInvocation_WithSingleConcurrency_GetsItsOwnContext_NotTheSharedOneEndpoint_Flush_Sees_Metric_First_Added_In_Awaited_Helper_And_Requests_Do_Not_Share_Metrics(UseMetrics / WithMetrics / both)When_Middleware_And_Filter_Are_Both_Used_The_Filter_Context_Ends_And_The_Request_Context_Is_Still_UsedWhen_UseMetrics_And_Endpoint_Resumes_On_Another_Thread_...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 inConcurrencyTestssimulate concurrent invocations, so they now run withAWS_LAMBDA_MAX_CONCURRENCY=4and restore the previous value inDispose.Test runs (net8.0 and net10.0 each, rebased on e2c6166):
dotnet test libraries/tests/AWS.Lambda.Powertools.Metrics.Tests: 116/116 passeddotnet 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 passedValidateLockplus allAsyncContextTests(19 tests), 30 runs with--filteron net10.0: 30/30 passeddotnet restore && dotnet build --configuration Release --no-restorefromlibraries/: succeeded, 0 errors, no IL trim/AOT warnings in MetricsMerge Danger
Door: two-way. The change is internal to
AWS.Lambda.Powertools.MetricsandMetrics.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.AspNetCorenow depends on new internalMetricsmethods, 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:
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.