Skip to content

fix(batch): remove Native AOT warnings from BatchProcessing - #1370

Merged
hjgraca merged 1 commit into
developfrom
fix/batch-aot-warnings
Nov 25, 2026
Merged

hjgraca merged 1 commit into
developfrom
fix/batch-aot-warnings

Conversation

@hjgraca

@hjgraca hjgraca commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Issue number: closes #1332

Summary

Changes

Removes the 12 Powertools-owned trim/AOT warnings that a Native AOT publish of a BatchProcessing app reports. It also fixes typed [BatchProcessor] handlers, which didn't work under Native AOT at all.

Warnings Where Fix
IL2026, IL3050 DynamoDbRecordDataExtractor.ExtractData serialized an anonymous type with reflection Fixed: a named internal DynamoDbRecordData in a source-generated BatchProcessingSerializationContext. The JSON is unchanged (a test pins it to the old output).
IL2026, IL3050 JsonDeserializationService.DeserializeWithFallback<T> Fixed: the reflection call moved into a [RequiresUnreferencedCode]/[RequiresDynamicCode] helper that is only called inside JsonSerializer.IsReflectionEnabledByDefault && RuntimeFeatureWrapper.IsDynamicCodeSupported, so ILC removes it. A #pragma is kept only for the Roslyn analyzer, which doesn't treat that check as a guard.
IL2026, IL3050 AotCompatibilityHelper.FallbackDeserialize<T> Removed: it was internal and nothing called it.
IL2075 ×2 BatchProcessorAttribute: GetMethod("Create") on the typed provider types Fixed: TypedRecordHandlerProvider and TypedRecordHandlerWithContextProvider are now annotated with PublicMethods.
IL2075 (GetMethods), IL2060 TypedBatchProcessingAspectHandler: searched the processor's runtime type for ProcessAsync Fixed: a private generic ProcessAsync<T> calls the processor through ITypedBatchProcessor<,>, and it is resolved with a statically known GetMethod.
IL3050 MakeGenericMethod(dataType) Suppressed, with the same reasoning as UniversalWrapperAspect (#1346): under Native AOT only reference types reach it, and those share canonical code. Value-type record data now fails with a clear NotSupportedException.
IL2075 (GetInterfaces) Reading T from the handler instance (provider-created handlers have no annotated type) Suppressed: we only look for ITypedRecordHandler<T> / ITypedRecordHandlerWithContext<T>. ProcessAsync<T> casts the handler to those interfaces and is always compiled, so ILC keeps them. The runtime check below covers both direct and provider-created handlers.

Call flow for typed handlers:

 TypedBatchProcessingAspectHandler.HandleAsync
-  handler.GetType().GetInterfaces()              -> T
-  processor.GetType().GetMethods() "ProcessAsync" -> MakeGenericMethod(T).Invoke(processor, ...)
+  GetHandlerDataType(handler)                    -> T
+  if Native AOT and T is a value type -> NotSupportedException
+  typeof(TypedBatchProcessingAspectHandler<,>).GetMethod(ProcessAsync).MakeGenericMethod(T).Invoke(this, ...)
+    ProcessAsync<T>
+      ITypedBatchProcessor.ProcessAsync(event, (ITypedRecordHandler[WithContext]<T>)handler, ...)

AotCompatibilityHelper.IsAotMode now reads RuntimeFeatureWrapper, so tests can simulate Native AOT. Value-type return types of [BatchProcessor] methods aren't covered here; #1345 handles those.

User experience

Before, under Native AOT (3.2.2 package), every typed [BatchProcessor] handler failed before processing any record:

sqs typed handler: threw InvalidOperationException: Handler type 'OrderHandler' does not implement ITypedRecordHandler<T> or ITypedRecordHandlerWithContext<T>.
kinesis typed provider: threw InvalidOperationException: Error during creation of typed record handler using provider: 'OrderHandlerProvider'.

After, typed handlers behave the same under Native AOT as under JIT. Two cases still fail under Native AOT, now with clear messages (both are documented in docs/utilities/batch-processing.md):

  • no JsonSerializerContext: AotCompatibilityException ("AOT compilation requires a JsonSerializerContext for type 'Order'...")
  • value-type record data: NotSupportedException ("Typed record handler 'ValueTypeHandler' handles 'Amount', a value type, which isn't supported when running as Native AOT...")

Evidence

AOT harness (.NET 10 Native AOT publish of a BatchProcessing app with TrimmerRootAssembly, packed from this branch):

  • Before (develop): BatchProcessing powertools=12 total=12
  • After: BatchProcessing powertools=0 total=0

Runtime check: a Native AOT app (no TrimmerRootAssembly, 0 IL warnings) on the packed build. It processes SQS, Kinesis and DynamoDB Streams batches, each with a failing record (and a bad-JSON SQS record). It uses typed handlers (direct, provider, with context, provider with context) and a traditional handler. The output matches the same app under JIT line for line:

sqs typed handler: failures=[m2,m3] handled=[1:10,4:40]
sqs typed provider + context: failures=[m2,m3] handled=[1:10@fn,4:40@fn]
kinesis typed handler + context: failures=[k2] handled=[1:1@fn,3:3@fn]
kinesis typed provider: failures=[k2] handled=[1:1,3:3]
dynamodb typed handler: failures=[d2] handled=[INSERT:1:2:d1,REMOVE:3:-:d3]
dynamodb traditional handler: failures=[d2] handled=[INSERT:1,REMOVE:3]

Tests: new NativeAot/NativeAotCompatibilityTests (simulated AOT through RuntimeFeatureWrapper):

ExtractData writes the same JSON as the old anonymous type         (pinned literal)
Deserialize / TryDeserialize without a context under AOT            -> AotCompatibilityException   (was: reflection fallback ran)
typed handler / provider / with context / context provider under AOT -> failures=[fail], successes=[1,3]
value-type record data under AOT                                    -> NotSupportedException       (was: no exception)
value-type record data under JIT                                    -> processes
ITypedRecordHandlerWithContext without an ILambdaContext argument   -> InvalidOperationException with guidance

dotnet test tests/AWS.Lambda.Powertools.BatchProcessing.Tests: 262/262 on net8.0 and 262/262 on net10.0. dotnet build --configuration Release from libraries/ succeeds with no IL warnings in BatchProcessing.

Merge Danger

Door: two-way

Internal changes plus two widened DynamicallyAccessedMembers annotations. Easy to revert.

Blast Radius: BatchProcessing

  • Under JIT, typed handlers now call the processor through ITypedBatchProcessor<,> instead of a public ProcessAsync found by reflection on the concrete type. This is the same for any processor that implements the interface normally.
  • An ITypedRecordHandlerWithContext<T> without an ILambdaContext argument now throws InvalidOperationException with guidance. Before, MethodInfo.Invoke threw an ArgumentException.
  • Trimmed apps that aren't AOT (IsReflectionEnabledByDefault=false) without a JsonSerializerContext now get AotCompatibilityException instead of STJ's "reflection-based serialization has been disabled" error.

Checklist

Is this a breaking change?

No.

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.

- DynamoDbRecordDataExtractor serializes a named type with a source-generated
  context instead of an anonymous type with reflection.
- JsonDeserializationService guards reflection-based deserialization with
  JsonSerializer.IsReflectionEnabledByDefault; remove the unused
  AotCompatibilityHelper.FallbackDeserialize.
- Typed [BatchProcessor] handlers call ProcessAsync<T> through the
  ITypedBatchProcessor interface from a statically known generic method, and
  reject value-type record data under Native AOT with a clear error.
- Annotate the typed handler provider properties with PublicMethods.

Closes #1332
@hjgraca hjgraca added bug Unexpected, reproducible and unintended software behaviour aot area/batch Batch 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
@sonarqubecloud

Copy link
Copy Markdown

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.10345% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.36%. Comparing base (57c40dc) to head (0e86436).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...sing/Internal/TypedBatchProcessingAspectHandler.cs 91.42% 1 Missing and 2 partials ⚠️
...ools.BatchProcessing/JsonDeserializationService.cs 83.33% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1370      +/-   ##
===========================================
+ Coverage    80.29%   80.36%   +0.06%     
===========================================
  Files          303      304       +1     
  Lines        12962    12960       -2     
  Branches      1551     1547       -4     
===========================================
+ Hits         10408    10415       +7     
+ Misses        2098     2090       -8     
+ Partials       456      455       -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 80c45ff into develop Nov 25, 2026
12 checks passed
@hjgraca
hjgraca deleted the fix/batch-aot-warnings branch November 25, 2026 18:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

aot area/batch Batch utility bug Unexpected, reproducible and unintended software behaviour documentation Improvements or additions to documentation size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Native AOT warnings in BatchProcessing

1 participant