Skip to content

Cache PropertyChanged/ChangingEventArgs on BindableProperty - #38083

Merged
kubaflo merged 16 commits into
dotnet:net11.0from
pictos:pj/cache-property-changes-eventargs
Sep 29, 2026
Merged

kubaflo merged 16 commits into
dotnet:net11.0from
pictos:pj/cache-property-changes-eventargs

Conversation

@pictos

@pictos pictos commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

This is a follow up of #34136.

Apple M4 Max · .NET SDK 11.0.100-rc.1 · BenchmarkDotNet 0.13.10 · Arm64 RyuJIT

Delta (current − net11.0; negative = current is faster/leaner):

Method Δ Mean (ns) Δ Mean (%) Δ Allocated (B) Δ Allocated (%)
Label_HeightRequest −0.70 −1.0% −48 −50.0%
Button_HeightRequest +1.56 +2.1% −48 −50.0%
Entry_HeightRequest +0.17 +0.2% −48 −50.0%
Label_SetBackground −6.98 −6.4% −48 −100.0%
Button_SetBackground −10.45 −9.2% −48 −100.0%
Entry_SetBackground −13.16 −11.6% −48 −100.0%
Label_SetCommonProperties_WithSubscriber +3.19 +0.7% −192 −22.6%
Button_SetCommonProperties_WithSubscriber +13.06 +2.4% −240 −25.4%
Entry_SetCommonProperties_WithSubscriber +10.25 +2.2% −192 −22.6%
SetSameValueOnDifferentControls +5.95 +2.8% −144 −100.0%

Issues Fixed

Fixes #34092

Copilot AI lite review requested due to automatic review settings September 1, 2026 22:47
@pictos
pictos temporarily deployed to copilot-pat-pool September 1, 2026 22:47 — with GitHub Actions Inactive
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 38083

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 38083"

@pictos
pictos temporarily deployed to copilot-pat-pool September 1, 2026 22:47 — with GitHub Actions Inactive
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@pictos! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @pictos! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@pictos
pictos temporarily deployed to copilot-pat-pool September 1, 2026 22:48 — with GitHub Actions Inactive
@kubaflo

This comment has been minimized.

@pictos
pictos temporarily deployed to copilot-pat-pool September 1, 2026 22:50 — with GitHub Actions Inactive
@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 1, 2026
@pictos
pictos temporarily deployed to copilot-pat-pool September 1, 2026 22:51 — with GitHub Actions Inactive
@github-actions github-actions Bot added the area-controls-general General issues that span multiple controls, or common base classes such as View or Element label Sep 1, 2026
@pictos
pictos temporarily deployed to copilot-pat-pool September 1, 2026 22:52 — with GitHub Actions Inactive

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.

🟡 Changes recommended

It introduces a confirmed null-key exception risk in the new cache path, adds an unbounded global cache with lifetime retention implications, and includes an unrelated new script not reflected in the PR description/title scope.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR aims to reduce allocations in BindableObject property notifications by caching PropertyChangedEventArgs / PropertyChangingEventArgs rather than allocating new instances per call, addressing the perf scenario in #34092. However, the current implementation uses global static caches keyed by propertyName (with behavioral/memory implications), and the PR also introduces a new activate.sh script that is not described by the PR metadata.

Changes:

  • Add global static ConcurrentDictionary caches for PropertyChangedEventArgs/PropertyChangingEventArgs keyed by property name.
  • Update BindableObject.OnPropertyChanged/OnPropertyChanging to use the cached instances.
  • Add a new repository-root activate.sh environment activation script (not mentioned in the PR description).
File summaries
File Description
src/Controls/src/Core/BindableProperty.cs Introduces global caches and helper methods for reusing event args instances.
src/Controls/src/Core/BindableObject.cs Switches property notification helpers to use the cached event args.
activate.sh Adds a new bash activation script for using a local .dotnet install.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 5
  • Review effort level: Lite

Comment thread activate.sh Resolved
Comment thread activate.sh Resolved
Comment thread activate.sh Resolved
MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 2, 2026
Copilot AI review requested due to automatic review settings September 2, 2026 03:08

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.

🟡 Changes recommended

The new cached-event-args implementation throws on null property names (behavior regression) and the activation scripts currently clobber pre-existing DOTNET_ROOT instead of restoring it on deactivate.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (4)

src/Controls/src/Core/BindableProperty.cs:269

  • ConcurrentDictionary.GetOrAdd throws for null keys, but OnPropertyChanged([CallerMemberName] string propertyName = null) allows callers to explicitly pass null (commonly meaning “all properties changed”). With the current implementation, OnPropertyChanged(null) / OnPropertyChanging(null) will start throwing ArgumentNullException instead of raising the event. Add a null fast-path that returns a cached args instance (or falls back to allocating) before hitting the dictionary.
		private static readonly ConcurrentDictionary<string, PropertyChangedEventArgs> s_changedArgsCache = new();
		private static readonly ConcurrentDictionary<string, PropertyChangingEventArgs> s_changingArgsCache = new();

		internal static PropertyChangedEventArgs GetCachedPropertyChangedEventArgs(string propertyName)
			=> s_changedArgsCache.GetOrAdd(propertyName, static name => new PropertyChangedEventArgs(name));

		internal static PropertyChangingEventArgs GetCachedPropertyChangingEventArgs(string propertyName)
			=> s_changingArgsCache.GetOrAdd(propertyName, static name => new PropertyChangingEventArgs(name));

activate.sh:66

  • Before overwriting DOTNET_ROOT, capture the current value so deactivate can reliably restore (or unset) it. Without this, even with a safer deactivate, users can’t get back to their previous DOTNET_ROOT after activating MAUI.
DIR="$( cd "$( dirname "$_SCRIPT_SOURCE" )" && pwd )"
_OLD_PATH="$PATH"
# Tell dotnet where to find itself
export DOTNET_ROOT="$DIR/.dotnet"
# Put dotnet first on PATH
export PATH="$DOTNET_ROOT:$PATH"

activate.ps1:38

  • Capture the current DOTNET_ROOT value (and whether it was set) before overwriting it, so deactivate can restore the prior environment correctly.
$_OLD_PATH = $env:PATH
# Tell dotnet where to find itself
$env:DOTNET_ROOT = Join-Path $PSScriptRoot '.dotnet'
# Put dotnet first on PATH
$env:PATH = "$env:DOTNET_ROOT$([IO.Path]::PathSeparator)$env:PATH"

activate.sh:5

  • These new activate.* environment scripts are not mentioned in the PR title/description (which focuses on caching PropertyChanged/ChangingEventArgs). Consider either documenting them in the PR description (including intended workflow/usage) or splitting them into a separate PR to keep scope focused and reviewable.
#!/bin/bash
#
# This file must be used by invoking "source activate.sh" from the command line.
# You cannot run it directly.
# To exit from the environment this creates, execute the 'deactivate' function.
  • Files reviewed: 4/4 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread activate.ps1 Resolved
Comment thread activate.sh Resolved
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 2, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 3 findings

See inline comments for details.

private static readonly ConcurrentDictionary<string, PropertyChangingEventArgs> s_changingArgsCache = new();

internal static PropertyChangedEventArgs GetCachedPropertyChangedEventArgs(string propertyName)
=> s_changedArgsCache.GetOrAdd(propertyName, static name => new PropertyChangedEventArgs(name));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[critical] Logic and Correctness — GetOrAdd rejects a null key, but OnPropertyChanged/OnPropertyChanging legally allow propertyName = null (the previous implementation constructed new PropertyChangedEventArgs(null)/new PropertyChangingEventArgs(null) successfully). Concrete failure: any derived BindableObject that raises OnPropertyChanged(null) to signal a broad refresh now throws ArgumentNullException during event dispatch.


internal ValidateValueDelegate ValidateValue { get; private set; }

private static readonly ConcurrentDictionary<string, PropertyChangedEventArgs> s_changedArgsCache = new();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Memory Leak Prevention — The new static ConcurrentDictionary<string, ...> caches retain every distinct property name for process lifetime with no bound/eviction. Concrete failure scenario: controls or app code that emits dynamic property names (for example per-item/per-key notifications) will monotonically grow these static caches and permanently retain strings/event-args that were previously collectible.

Comment thread activate.sh Outdated

# Make sure the script is being sourced rather than executed; otherwise the
# environment changes below are discarded when the child process exits.
if [ -n "${BASH_SOURCE:-}" ] && [ "${BASH_SOURCE[0]}" = "${0}" ] ; then

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — The 'must be sourced' guard only handles bash (BASH_SOURCE[0] == $0) and does not detect direct execution under zsh. Concrete failure: running ./activate.sh in zsh proceeds, prints the success banner, and exits, but environment changes are lost because it ran in a child process.

MauiBot

This comment was marked as outdated.

Copilot AI review requested due to automatic review settings September 29, 2026 16:36
@kubaflo
kubaflo force-pushed the pj/cache-property-changes-eventargs branch from 67a9db0 to 1182255 Compare September 29, 2026 16:36
@kubaflo

kubaflo commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15504335 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

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.

Copilot review overview

🟡 Changes recommended

Avoid eager 2048-entry cache allocation during BindableProperty initialization.

Review effort: Lite
Findings: 1 Medium severity

Open (1)

throw new ArgumentOutOfRangeException(nameof(capacity), "capacity must be at least 1");
}

_entries = new ConcurrentDictionary<string, TArgs>(1, capacity, StringComparer.Ordinal);

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@pictos — new AI review results are available based on commit 1182255.

Gate Passed Confidence Low Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: net11.0 · Merge base: 130a9f62

✅ Verified (new API / feature) — this PR adds new API and a test that references it in the same project, so reverting the fix un-compiles the test: there is no valid "fails without the fix" baseline to establish (a compile-coupled baseline). The gate instead verified the fix by a clean build + pass with the fix, so this is a real PASS rather than a non-committal INCONCLUSIVE.

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 PropertyChangeEventArgsCacheUnitTests PropertyChangeEventArgsCacheUnitTests 🛠️ BUILD ERROR ✅ PASS — 52s
🔴 Without fix — 🧪 PropertyChangeEventArgsCacheUnitTests: 🛠️ BUILD ERROR · 62s

Error-relevant lines (filtered from the build log):

/home/vsts/work/1/s/src/Controls/tests/Core.UnitTests/PropertyChangeEventArgsUnitTests.cs(11,10): error CS0246: The type or namespace name 'PropertyChangeEventArgsCache<>' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj]
🟢 With fix — 🧪 PropertyChangeEventArgsCacheUnitTests: PASS ✅ · 52s

(no coded error found; showing last 1200 chars)

/s/artifacts/bin/Controls.Core.UnitTests/Debug/net11.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v11.0)
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 11.0.0-rtm.26473.115)
[xUnit.net 00:00:00.19]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:01.41]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:01.43]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
  Passed StillReturnsCorrectArgsForNamesItRefusedToCache [6 ms]
  Passed DistinctNamesGetDistinctArgs [< 1 ms]
  Passed ReturnsTheSameInstanceForTheSameName [< 1 ms]
  Passed ComparesNamesOrdinally [< 1 ms]
  Passed KeepsServingTheNamesItCachedOnceFull [< 1 ms]
  Passed StaysBoundedUnderConcurrentMisses [8 ms]
  Passed RejectsAMissingFactory [< 1 ms]
  Passed RejectsAnInvalidCapacity [< 1 ms]
  Passed StopsGrowingAtCapacity [3 ms]
[xUnit.net 00:00:01.52]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed ReturnsArgsCarryingTheRequestedName [< 1 ms]
  Passed ClearMakesRoomAgain [1 ms]
Test Run Successful.
Total tests: 11
     Passed: 11
 Total time: 2.1964 Seconds

⚠️ Failure Details

  • 🛠️ PropertyChangeEventArgsCacheUnitTests without fix: build failed before tests could run
    • /home/vsts/work/1/s/src/Controls/tests/Core.UnitTests/PropertyChangeEventArgsUnitTests.cs(11,10): error CS0246: The type or namespace name 'PropertyChangeEventArgsCache<>' could not be found (are you ...
📁 Fix files reverted (3 files)
  • src/Controls/src/Core/BindableObject.cs
  • src/Controls/src/Core/BindableProperty.cs
  • src/Controls/src/Core/Element/Element.cs

New files (not reverted):

  • src/Controls/src/Core/Internals/PropertyChangeEventArgsCache.cs

📋 Pre-Flight — Context & Validation

PR #38083 Pre-Flight

Context

  • Title: Cache PropertyChangedEventArgs / PropertyChangingEventArgs on BindableProperty
  • Base: net11.0 at 130a9f62c1b055ebcf42cdadc37a55cb732cff3c
  • Review commit: 0bed470907bb03c605c5a231a35ce975559b6994
  • Issue: #34092 reports repeated event-args allocations on every BindableObject.SetValue notification and a second PropertyChangedEventArgs allocation when Element forwards notifications to effects.
  • Goal: Remove these recurring allocations without changing notification ordering, virtual override dispatch, nested notification behavior, null-name semantics, or plain CLR-property notifications.
  • Platform: Android. The detected tests are platform-neutral Controls unit tests, so no Android device runner is required.

Existing PR Approach

The PR:

  1. Adds lazy PropertyChangedEventArgs and PropertyChangingEventArgs fields to each long-lived BindableProperty.
  2. Parks the currently notifying BindableProperty on BindableObject while calling the existing virtual OnPropertyChanged(string) / OnPropertyChanging(string) APIs, restoring it in finally to support re-entrant notifications.
  3. Uses a bounded, process-wide PropertyChangeEventArgsCache<TArgs> for notifications raised only by property name, including explicit singleton handling for a null property name.
  4. Reuses the resolved changed args when Element forwards a notification to effects.
  5. Adds focused cache, override, nesting, null-name, and concurrency tests plus a benchmark.

Changed Files

  • src/Controls/src/Core/BindableObject.cs
  • src/Controls/src/Core/BindableProperty.cs
  • src/Controls/src/Core/Element/Element.cs
  • src/Controls/src/Core/Internals/PropertyChangeEventArgsCache.cs (new)
  • src/Controls/tests/Core.UnitTests/PropertyChangeEventArgsUnitTests.cs (new)
  • src/Core/tests/Benchmarks/Benchmarks/PropertyNotificationBenchmarker.cs (new)

Direct Diff Assessment

The behavioral seam is the public/protected virtual name-based notification API. A viable alternative must still dispatch those overrides and cannot simply bypass OnPropertyChanged or OnPropertyChanging. It must also distinguish the originating BindableProperty from a renamed notification and preserve the outer origin across nested changes.

The current fallback cache is deliberately bounded at 2,048 names and stops admitting misses once full. Its concurrent admission counter is tested to stay within capacity. Any alternative should avoid an unbounded static cache and should not regress the zero-allocation hot path for bindable properties.

The gate already passed. It classified the baseline as compile-coupled because the PR adds both the cache implementation and tests that reference it. The gate restored three modified production files but reported src/Controls/src/Core/Internals/PropertyChangeEventArgsCache.cs as a new production file. Per the try-fix restoration contract, a non-empty baseline NewFiles array may block an attempt before editing; such a result must be recorded honestly rather than bypassing restoration safeguards.

Narrow Validation

Do not rerun the gate and do not run a full suite.

Primary test:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~PropertyChangeEventArgsCacheUnitTests"

Direct notification regressions from the same PR:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~PropertyChangeEventArgsUnitTests"

The gate verified 11 cache tests pass with the PR. Regression cross-reference reported no overlap with recent labeled bug-fix PRs touching these files.


🔬 Code Review — Deep Analysis

Code Review — PR #38083

Independent Assessment

What this changes: Reuses PropertyChangedEventArgs and PropertyChangingEventArgs on the bindable-property notification path, while preserving the protected virtual name-based notification hooks. A per-object parked BindableProperty carries the origin through virtual dispatch and nested notifications; notifications without a BindableProperty use bounded process-wide name caches. Element also reuses the resolved changed args for effects.

Inferred motivation: Remove recurring event-args allocations from a framework-wide hot path without changing notification order, override behavior, null-name semantics, or re-entrant property changes.

Approach assessment: The abstraction is sound. The property-owned args provide a zero-allocation steady-state path, the try/finally save-and-restore preserves nested dispatch, renamed overrides correctly fall back by name, and the fallback cache is now bounded with atomic slot reservation.

Reconciliation with PR Narrative

Author claims: This follows #34136 and reduces allocations from bindable-property notifications, with benchmark results showing 48-byte reductions in common property sets and larger reductions when several properties are set.

Agreement/disagreement: The implementation matches that goal and preserves the relevant behavior. The description is missing the design details and validation added by the submitted diff, but its performance claim is directionally consistent with the code.

Prior Review Reconciliation

Prior ❌ Error Finding Source Status Evidence
Null property names throw in ConcurrentDictionary MauiBot / Copilot on an earlier head ✅ Fixed Current head routes null names to dedicated singleton args and tests both direct cache access and subscriber notification.
Arbitrary notification names are retained without bound MauiBot on an earlier head ✅ Fixed PropertyChangeEventArgsCache<TArgs> has a 2,048-entry ceiling and refuses new names after reaching it.
Concurrent misses can exceed capacity MauiBot on an earlier head ✅ Fixed Current head reserves with Interlocked.Increment, releases rejected/lost reservations, and includes a parallel boundedness test.
Activation scripts were unrelated and unsafe MauiBot on an earlier head 🔄 Obsolete Those files are absent from the submitted six-file diff.

The single authorized maui-expert-reviewer pass produced no actionable inline findings (inline-findings.json is []).

Blast Radius Assessment

  • Runs for all instances: The property-owned path runs for every changed BindableProperty; the fallback static caches run for explicit name-only notifications.
  • Startup impact: BindableProperty type initialization eagerly constructs two ConcurrentDictionary instances with an initial capacity of 2,048 each.
  • Static/shared state: Two process-wide caches retain at most 2,048 changed and 2,048 changing names; the bound prevents unbounded lifetime retention.

CI Status

  • Required-check result: Pending on PR head 11822554033f4e9f0a2a6c2e0d2b401d40e93364; public check-runs show the Windows Helix unit-test jobs succeeded while broader MAUI jobs remain queued/in progress.
  • Classification: Undetermined until required CI completes.
  • Action taken: Did not rerun the trusted Gate. The provided Gate passed the focused cache tests (11/11), and confidence remains capped at low because required CI is pending.

Findings

⚠️ Warning — The fallback dictionaries eagerly allocate for the maximum entry ceiling

PropertyChangeEventArgsCache<TArgs> passes capacity as ConcurrentDictionary's initial bucket capacity at src/Controls/src/Core/Internals/PropertyChangeEventArgsCache.cs:75. Consequently, both static fallback caches reserve for 2,048 entries during BindableProperty initialization even when an application never raises a name-only notification. This contradicts the class comment that the dictionary grows with names seen and adds avoidable startup memory. Keep the logical _capacity ceiling but use a small initial dictionary capacity.

Failure-Mode Probing

  • Dynamic/generated names beyond the working set: The cache stops at 2,048 entries, returns correct fresh args for misses, and does not evict useful startup entries.
  • Null “all properties changed” notifications: Dedicated null-name singletons preserve the previous valid behavior without passing null into ConcurrentDictionary.
  • Nested notifications and overrides: The parked property is saved and restored in finally; nested changes and overrides that rename before calling base resolve the correct args.
  • Concurrent misses: Atomic reservation prevents different names from exceeding the bound; same-name losers release their reservation and return the winning cached instance when available.
  • Cross-thread notifications on one BindableObject: A race can force the name-cache fallback, but the emitted PropertyName remains correct. PropertyChangedEventArgs exposes only the name, so this does not create an observable semantic mismatch beyond instance identity, which was not previously stable.

External Output Contract

Not applicable.

Verdict: NEEDS_DISCUSSION

Confidence: low

Summary: No correctness blocker was found, and the trusted focused Gate passes. Separating the dictionary's small initial capacity from its 2,048-entry logical ceiling is a low-risk improvement that better aligns startup cost with the allocation-reduction goal; required CI is still pending.


🛠️ Try-Fix — Analysis & Comparison

Aggregate Try-Fix Results

Candidate 1 — gpt-5.3-codex

Result: Blocked

The mandatory baseline script rejected pre-existing unrelated tracked worktree changes before it could create the restoration state and modification allow-list. No implementation approach, source edit, or test run was permitted. The code diff is empty, inline self-review found no issues in that empty diff, and the exact restore command completed with the expected no-state result.

Detailed narrative: ../try-fix-1/content.md
Skill artifacts: attempt-1/

Candidate 2 — gpt-5.6-sol

Result: Blocked

After reading Candidate 1's recorded result without reopening or rerunning it, Candidate 2 independently invoked the required workflow. The mandatory baseline script again rejected the same eight unrelated tracked worktree changes before creating restoration state or a modification allow-list. Candidate 2 therefore produced no implementation approach, source edit, or test run. The code diff is empty, inline self-review found no issues in that empty diff, and the exact restore command completed with the expected no-state result.

Detailed narrative: ../try-fix-2/content.md
Skill artifacts: attempt-2/

Aggregate Outcome

Two bounded invocations were completed in the required order and no additional agents were launched. Both were blocked before mechanism design by the repository's baseline safety precondition. Consequently, STEP 5a produced zero implementable or empirically tested alternative fix candidates; it does not claim a Pass or infer correctness from code inspection. The existing PR fix and gate result remain unchanged for STEP 5b.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current title abbreviates the exact event-args types, while the description is mostly benchmark output and omits the submitted implementation, compatibility safeguards, tests, and cross-platform scope.

Recommended title

Controls: Cache PropertyChangedEventArgs and PropertyChangingEventArgs

Recommended description

### Description of Change

This is a follow-up to #34136 that removes repeated `PropertyChangedEventArgs` and `PropertyChangingEventArgs` allocations from `BindableObject` property notifications.

The change:

- Lazily stores `PropertyChangedEventArgs` and `PropertyChangingEventArgs` on each long-lived `BindableProperty`.
- Preserves the existing protected virtual `OnPropertyChanged(string)` and `OnPropertyChanging(string)` dispatch by temporarily tracking the originating `BindableProperty`, including nested/re-entrant notifications and overrides that rename a notification.
- Uses bounded process-wide caches for name-only notifications that do not originate from a `BindableProperty`, with dedicated handling for a null property name.
- Reuses the resolved `PropertyChangedEventArgs` when `Element` forwards property changes to effects.
- Adds focused unit coverage for reuse, null names, virtual overrides, nested notifications, bounded capacity, and concurrent cache misses, plus a property-notification benchmark.

The implementation is in shared Controls code and applies across platforms. Android is the requested validation platform; there is no Android-specific code path or public API change.

### Benchmark

Apple M4 Max · .NET SDK 11.0.100-rc.1 · BenchmarkDotNet 0.13.10 · Arm64 RyuJIT

Delta (current − net11.0; negative = current is faster/leaner):

| Method | Δ Mean (ns) | Δ Mean (%) | Δ Allocated (B) | Δ Allocated (%) |
|---|---:|---:|---:|---:|
| Label_HeightRequest | −0.70 | −1.0% | −48 | −50.0% |
| Button_HeightRequest | +1.56 | +2.1% | −48 | −50.0% |
| Entry_HeightRequest | +0.17 | +0.2% | −48 | −50.0% |
| Label_SetBackground | −6.98 | −6.4% | −48 | −100.0% |
| Button_SetBackground | −10.45 | −9.2% | −48 | −100.0% |
| Entry_SetBackground | −13.16 | −11.6% | −48 | −100.0% |
| Label_SetCommonProperties_WithSubscriber | +3.19 | +0.7% | −192 | −22.6% |
| Button_SetCommonProperties_WithSubscriber | +13.06 | +2.4% | −240 | −25.4% |
| Entry_SetCommonProperties_WithSubscriber | +10.25 | +2.2% | −192 | −22.6% |
| SetSameValueOnDifferentControls | +5.95 | +2.8% | −144 | −100.0% |

### Issues Fixed

Fixes #34092

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

pr-plus-reviewer keeps the submitted fix and applies one focused review improvement: the two bounded fallback dictionaries now start with 31 buckets (or the configured maximum when smaller) instead of eagerly sizing each dictionary to the full 2,048-entry ceiling. This preserves the admission limit, comparer, concurrency behavior, and notification semantics while avoiding unnecessary process-startup memory.

Comparative Analysis

Rank Candidate Implementation Validation Assessment
1 pr-plus-reviewer Raw PR plus a small initial ConcurrentDictionary capacity, independent of the 2,048-entry logical ceiling diff --check passed. Both required focused commands were attempted once but were blocked during project compilation by pre-existing RS0030 banned-API errors in unrelated BindableLayoutTests, ControlsMapperTests, HandlerLifeCycleTests, HostBuilderHandlerTests, and ShellTests; no selected test executed. Winner. Removes the raw PR's avoidable eager bucket allocation without changing cache behavior. Validation uncertainty is explicit; this was a build-environment/source-overlay blocker, not a regression-test failure in the candidate.
2 pr Per-BindableProperty lazy args, nested-safe virtual-dispatch parking, bounded fallback caches, null-name singletons, and effect forwarding reuse Trusted Gate passed all 11 focused cache tests. Public PR check-runs show Windows Helix unit tests succeeded; broader required CI remained pending at review time. Correct and well-tested core design, with no expert inline findings. Ranked below the winner because both static fallback caches eagerly allocate for 2,048 buckets during BindableProperty initialization.
3 try-fix-1 No implementation; empty diff Blocked before editing or testing because baseline establishment rejected unrelated tracked changes. Not an implementable or empirically evaluated alternative.
4 try-fix-2 No implementation; empty diff Blocked before editing or testing by the same baseline safety precondition. Not an implementable or empirically evaluated alternative.

Expert Review

The single authorized maui-expert-reviewer pass wrote inline-findings.json as an empty JSON array. Earlier error-level findings on prior heads are resolved: null names use dedicated singleton args, arbitrary names are bounded, capacity reservation is atomic, and unrelated activation scripts are no longer in the submitted diff.

The remaining current-head review concern is performance rather than correctness: new ConcurrentDictionary<string, TArgs>(1, capacity, ...) uses the 2,048-entry maximum as the initial bucket capacity. pr-plus-reviewer addresses that concern surgically.

Validation Evidence

  • Trusted raw-PR Gate: PASS — 11/11 PropertyChangeEventArgsCacheUnitTests.
  • Regression cross-reference: CLEAN — no overlap with recent labeled bug-fix PRs.
  • Candidate sandbox identity: /home/vsts/work/_temp/pr-38083-pr-plus-reviewer at immutable baseline f2f9fd8bce961207c690b7f2d6f08e129d1e05e6.
  • Candidate patch hygiene: PASS — git diff --check against the immutable baseline.
  • Candidate focused validation: BLOCKED before test execution by unrelated RS0030 compile errors. Per the execution contract, no repair or retry was attempted.
  • Candidate artifacts: pr-plus-reviewer/reviewer.patch, pr-plus-reviewer/candidate.patch, and the two complete focused validation logs.

Required Change

Apply pr-plus-reviewer/reviewer.patch to retain the 2,048-entry cache ceiling while using a small initial dictionary capacity. Because the submitted PR does not yet contain that winning change, the recommendation is REQUEST CHANGES.


📱 UI Tests — Button,Label,Layout

Detected UI test categories: Button,Label,Layout

✅ Deep UI tests — 422 passed, 0 failed, 7 skipped across 3 categories on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Button 104/106 (2 skipped) ✓ —
Label 123/125 (2 skipped) ✓ —
Layout 195/198 (3 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: The submitted design is correct, but pr-plus-reviewer removes avoidable eager allocation by separating the fallback dictionary's 31-bucket initial size from its 2,048-entry logical ceiling. Its focused validation was blocked before test execution by unrelated pre-existing RS0030 errors, while the raw PR's trusted Gate passed.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-win AI found a better alternative fix than the PR and removed s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-review-in-progress AI review is currently running for this PR labels Sep 29, 2026
@kubaflo
kubaflo merged commit 8a19768 into dotnet:net11.0 Sep 29, 2026
160 of 169 checks passed
@github-actions github-actions Bot added this to the .NET 11.0-rc2 milestone Sep 29, 2026
@pictos
pictos deleted the pj/cache-property-changes-eventargs branch September 29, 2026 23:03
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 30, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-general General issues that span multiple controls, or common base classes such as View or Element community ✨ Community Contribution s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants