Skip to content

Build the DataProtection AAD template lazily - #70192

Merged
DeagleGross merged 1 commit into
mainfrom
perf/dataprotection-lazy-aad
Nov 5, 2026
Merged

DeagleGross merged 1 commit into
mainfrom
perf/dataprotection-lazy-aad

Conversation

@davidfowl

Copy link
Copy Markdown
Member

Build the DataProtection AAD template lazily

Description

Every KeyRingBasedDataProtector built its additional authenticated data (AAD) template (magic || keyId || purposeCount || purposes…, UTF-8 encoded) in its constructor. In a purpose chain such as provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2"), plus the application discriminator that AddDataProtection adds, every intermediate protector built and encoded a template for its prefix of the chain. That is O(n²) UTF-8 work, but only the leaf protector ever protects or unprotects.

The template is now built on the first Protect/Unprotect (GetAadForKey) and published with Interlocked.CompareExchange. The cache works as before: the template is cached per protector instance and updated for the default key on protect. To keep CreateProtector behavior unchanged, the constructor still eagerly validates the newly added purpose with the same SecureUtf8Encoding.GetByteCount. An invalid purpose, such as a lone surrogate, still throws EncoderFallbackException from CreateProtector. Earlier purposes in the chain were already validated when their protectors were created (the only constructor callers are KeyRingBasedDataProtectionProvider.CreateProtector with no prior purposes, and KeyRingBasedDataProtector.CreateProtector with its own validated Purposes).

Found by profiling (EventPipe allocation sampling): BuildAadTemplateBytes accounted for about 60% of allocations in CreateProtector chains.

Benchmarks

Linux x64, 2 cores, BenchmarkDotNet in-process, 3 interleaved rounds vs main (median). Provider from AddDataProtection (includes the app discriminator), default algorithms.

Scenario main PR main alloc PR alloc
CreateProtector(cookie chain) only 0.47 us 0.19 us (-59%) 776 B 344 B (-56%)
CreateProtector(cookie chain) + Protect 100 B 10.59 us 10.57 us 2,296 B 2,024 B (-12%)
CreateProtector(antiforgery, single purpose) + Protect 100 B 10.14 us 10.05 us 1,672 B 1,680 B (+8 B)

The single-purpose case has no intermediate protectors to save. It pays 8 bytes for the extra reference kept in the template struct.

Security reasoning

  • AAD bytes unchanged: the same BuildAadTemplateBytes builds the template from the same purposes, and the key id is written exactly as before. A new test checks that the lazily built AAD equals the eagerly built template. Existing tests cover byte-level compatibility of BuildAadTemplateBytes (ReturnsSameResultAsPreviousImplementation) and protect/unprotect round-trips.
  • No sharing across purposes: the template remains private state of a single protector instance and is derived only from that protector's own purposes. Nothing is shared between protectors or reachable by callers.
  • Thread safety: the first build is published with Interlocked.CompareExchange, so concurrent first callers agree on one immutable template (new concurrency test). The existing Volatile read/write logic for key changes is unchanged.
  • Exceptions unchanged: invalid purposes still throw from CreateProtector (new test). No public API change, no PublicAPI.*.txt changes, no unsafe code added. No crypto, comparison or validation logic is touched, and the key ring is still not resolved by CreateProtector.

Overlap

No overlap with #70146 (managed encryptor internals), #70187 (string overloads) or #70191 (TimeLimited).

Tests

Microsoft.AspNetCore.DataProtection.Tests: 340 passed, including 3 new tests.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Intermediate protectors in a purpose chain are only used to create child
protectors, so defer building their additional authenticated data template
until first Protect/Unprotect. The newest purpose is still validated eagerly.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 16:11
@github-actions github-actions Bot added the area-dataprotection Includes: DataProtection label Oct 31, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The review lacks a frozen evidence bundle with pinned head/base revisions and existing feedback, preventing independent verification of revision matching and feedback deduplication.

No open issues 🎉

What changed in this PR

This PR reduces DataProtection purpose-chain construction work by deferring additional authenticated data (AAD) template creation until the first protect or unprotect operation.

Changes:

  • Lazily builds and atomically publishes each protector’s AAD template, avoiding template allocations for unused intermediate protectors.
  • Preserves eager validation of newly added purposes and existing per-key caching behavior.
  • Adds tests for invalid-purpose exceptions, AAD byte compatibility, cache reuse, and concurrent first use.
File Description
src/​DataProtection/​DataProtection/​test/​Microsoft.AspNetCore.DataProtection.Tests/​KeyManagement/​AdditionalAuthenticatedDataTemplateTests.cs Adds validation, compatibility, caching, and concurrency tests.
src/​DataProtection/​DataProtection/​src/​KeyManagement/​KeyRingBasedDataProtector.cs Defers AAD template construction while preserving eager purpose validation.

Review effort: Balanced

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@DeagleGross
DeagleGross merged commit c6f4231 into main Nov 5, 2026
29 checks passed
@DeagleGross
DeagleGross deleted the perf/dataprotection-lazy-aad branch November 5, 2026 16:49
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 5%

No docs needed: internal refactoring (lazy AAD template construction) with unchanged behavior.

Documentation surfaces considered

  • Conceptual article: Not required — Internal implementation optimization; no public API or observable behavior change.
  • Migration guidance: Not required — No user action needed when upgrading.
  • Breaking change: Not required — Invalid purposes still throw the same exception; no compatibility impact.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 3fc4d951 Deployed Nov 5, 2026 by DeagleGross via conclusion #199
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-dataprotection Includes: DataProtection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants