Skip to content

fix(common): support value-type returns for [Idempotent] and [BatchProcessor] under Native AOT - #1371

Merged
hjgraca merged 1 commit into
developfrom
fix/aot-value-type-returns
Nov 25, 2026
Merged

hjgraca merged 1 commit into
developfrom
fix/aot-value-type-returns

Conversation

@hjgraca

@hjgraca hjgraca commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Issue number: closes #1345

Summary

Changes

[Idempotent] and [BatchProcessor] (and [Logging], which uses the same aspect) go through UniversalWrapperAspect. It built each handler with MakeGenericMethod(WrapSync<T> / WrapAsync<T>) plus a compiled expression tree. Under Native AOT, value-type instantiations have no native code, so since #1346 these methods threw a clear NotSupportedException.

The aspect now builds handlers from plain generic closures, and names the instantiations ILC needs:

 CreateMethodHandler(returnType)
-  T = VoidTaskResult | T of Task<T> | returnType
-  if AOT && T is value type -> throw NotSupportedException
-  MakeGenericMethod(WrapSync/WrapAsync, T) + Expression.Compile()
+  void            -> CreateSyncHandler<object>
+  Task            -> CreateTaskHandler: awaits the Task, wrappers see Task<object>
+  int, long, bool, double, decimal, Guid, DateTime (direct or Task<T>)
+                  -> CreateHandler<int>(...) ...   // written out, so ILC compiles WrapSync<int>/WrapAsync<int> and the overrides
+  other value type under AOT -> NotSupportedException (names method, type, attribute)
+  anything else   -> MakeGenericMethod(CreateSyncHandler/CreateAsyncHandler, T)   // reference types share canonical code
  • A plain Task no longer needs Task<VoidTaskResult>, a value type we can't name in code. The wrappers see Task<object>, and the result is a placeholder object, which serializes as {}. That is the same value VoidTaskResult was stored as before, so idempotency records stay compatible in both directions.
  • System.Linq.Expressions is no longer used. Wrapper order is unchanged: the last wrapper runs first, which a new test covers.
  • IdempotencySerializationContext now registers int, long, bool, double, decimal, Guid and DateTime, so storing and replaying these results under AOT works without the user adding them to their own context. This only adds new generated properties to that public context.
  • The IL3050 suppression stays on the one method that still calls MakeGenericMethod, with an updated justification.
  • Docs: the "Return types under Native AOT" warnings in idempotency.md and batch-processing.md now list what's supported and what still throws (user structs, enums, int?, ValueTask<T>).

User experience

Under Native AOT, [Idempotent] public async Task Handler(string p) or [BatchProcessor(...)] public int Handler(SQSEvent e):

  • Before: NotSupportedException: 'Fns.Handler' returns 'Task', which IdempotentAttribute can't wrap when running as Native AOT...
  • After: works. For [Idempotent], the second call with the same payload returns the stored result.

User-defined structs still aren't supported under AOT. They now get this message:

'IdemFns.Struct' returns 'UserStruct', which IdempotentAttribute can't wrap when running as Native AOT. Under Native AOT the supported return types are void, Task, reference types (for example a class, record or string), and int, long, bool, double, decimal, Guid or DateTime, either directly or as Task. Return one of these types instead, for example by wrapping the value in a class or record.

JIT behaviour is the same for every return type.

Evidence

Native AOT runtime (.NET 10, osx-arm64, local harness, packed develop vs this branch). [Idempotent] uses an in-memory BasePersistenceStore, and each method is called twice with the same payload. OK means the handler ran once and the second call returned the stored value. The user's JsonSerializerContext registers only UserStruct. [BatchProcessor] uses one SQS record and an IRecordHandler.

Return type JIT (develop / this PR) AOT [Idempotent] develop AOT [Idempotent] this PR AOT [BatchProcessor] develop AOT [BatchProcessor] this PR
void same both IdempotencyConfigurationException1 IdempotencyConfigurationException1 OK OK
string, Task<string> OK / OK OK OK OK OK
int, long, bool, double, decimal, Guid, DateTime OK / OK NotSupportedException OK NotSupportedException OK
Task<T> of the types above OK / OK NotSupportedException OK NotSupportedException OK
Task (async, and non-async Task.CompletedTask) OK / OK NotSupportedException OK (stored as {}) NotSupportedException OK
UserStruct, Task<UserStruct> OK / OK NotSupportedException NotSupportedException (new message) NotSupportedException NotSupportedException (new message)

1 Idempotency rejects void by design, on JIT too.

Under JIT, Task methods store {} on both develop and this PR.

AOT binary size of the harness: 4,540,304 bytes on develop, 4,092,544 bytes with this PR (no System.Linq.Expressions).

Native AOT publish warnings (per-package harness, Powertools-owned): Idempotency 0, Idempotency usage 0, Logging 0, Logging usage 0 (all unchanged). BatchProcessing 12, the same 12 as on develop (tracked in #1332). None of them are in UniversalWrapperAspect.

Unit tests (AOT simulated with RuntimeFeatureWrapper.SetIsDynamicCodeSupported(false)):

Common  UniversalWrapperAspect.Handle
  AOT + int|long|bool|double|decimal|Guid|DateTime        -> wrapper gets T = that type, value returned   (red before, green after)
  AOT + Task<same types>                                   -> wrapper gets T = that type, value returned   (red before, green after)
  AOT + Task | Task.CompletedTask | faulted Task           -> wrapper runs, task awaited, exception kept   (red before, green after)
  AOT + UserStruct | Task<UserStruct> | ValueTask<int>     -> NotSupportedException naming method + type
  JIT + UserStruct | Task<UserStruct>                      -> works (reflection path)
  several wrappers                                         -> last wrapper runs first (same as before)
Idempotency  [Idempotent] + in-memory store, AOT simulated
  int, long, bool, double, decimal, Guid, DateTime, Task<int|decimal|DateTime> -> 2nd call replays stored value (decimal/Guid/DateTime red before the context change)
  Task                                                     -> 2nd call replayed, stored response is "{}"
  UserStruct                                               -> NotSupportedException
BatchProcessing  [BatchProcessor], AOT simulated
  int, Task<bool>, Task -> batch processed, value returned; UserStruct -> NotSupportedException
Test project net8.0 net10.0
Common.Tests 104 passed, 1 skipped (existing skip) 104 passed, 1 skipped
BatchProcessing.Tests 257 passed 257 passed
Idempotency.Tests (incl. DynamoDB via Testcontainers) 104 passed 104 passed

Full Release build from libraries/ (dotnet build --configuration Release --no-restore): 0 errors, no warnings in the changed files.

Merge Danger

Door: two-way

Reverting restores the expression-tree path. No public API is removed. IdempotencySerializationContext gains generated properties for the new types, which is additive.

Blast Radius: moderate

Every package that includes Common runs this code for every [Idempotent], [BatchProcessor] and [Logging] method, on JIT and AOT. Behaviour changes to watch for:

  • A custom UniversalWrapperAttribute subclass now sees T = object instead of VoidTaskResult for methods that return a plain Task. VoidTaskResult is internal to the BCL, so code can't have relied on the type by name.
  • For idempotent Task methods, a response hook replaying a record now gets a JsonElement (deserialized as object) instead of a boxed VoidTaskResult. The hook result is ignored for Task anyway.
  • Handlers no longer use Expression.Compile(), which runs interpreted under AOT. Each wrapper allocates a closure per call, similar to the nested lambdas the compiled expression created.

Not covered here: JIT apps that call WithJsonSerializationContext() lose reflection-based serialization for types that aren't in their context. For example, a string payload fails with "JsonTypeInfo metadata for type 'System.String' was not provided". This already happens on develop, and this PR doesn't change it.

Checklist

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.

…ocessor] under Native AOT

Build UniversalWrapperAspect handlers from generic closures instead of
MakeGenericMethod over WrapSync/WrapAsync plus compiled expression trees.
Plain Task is wrapped as Task<object>, and int, long, bool, double,
decimal, Guid and DateTime (directly or as Task<T>) are instantiated
explicitly so ILC compiles them. Other value types still fail under AOT
with a clear NotSupportedException.

Register the same primitives in IdempotencySerializationContext so their
results are stored and replayed under AOT without user registration.

Closes #1345
@hjgraca hjgraca added bug Unexpected, reproducible and unintended software behaviour area/common Core Powertools utility aot area/idempotency 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 98.55072% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 80.36%. Comparing base (57c40dc) to head (479aa13).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...owertools.Common/Aspects/UniversalWrapperAspect.cs 98.55% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1371      +/-   ##
===========================================
+ Coverage    80.29%   80.36%   +0.07%     
===========================================
  Files          303      303              
  Lines        12962    12990      +28     
  Branches      1551     1560       +9     
===========================================
+ Hits         10408    10440      +32     
+ Misses        2098     2095       -3     
+ 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 6aa382d into develop Nov 25, 2026
12 checks passed
@hjgraca
hjgraca deleted the fix/aot-value-type-returns branch November 25, 2026 18:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

aot area/batch Batch utility area/common Core Powertools utility area/idempotency 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: [Idempotent] and [BatchProcessor] don't support value-type returns under Native AOT

1 participant