You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[WIP] Fix LastContractView to restore previous names of unknown discriminator models - #12601
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.
This section details on the original issue you should resolve
<issue_title>LastContractView - Restore Previous Names of Unknown Discriminator Models</issue_title>
<issue_description>### Clear and concise description of the problem
For every discriminated base model, the generator synthesizes a fallback model named Unknown{InputBaseModelName} (InputModelType.DiscriminatedSubtypes) and references it from the public base through [PersistableModelProxy(typeof(UnknownX))] (MrwSerializationTypeDefinition).
The unknown model is generated internal by default, but it is public when custom code declares it so (ModelProvider.BuildDeclarationModifiers takes accessibility from the custom code view). Either way its name is part of the checked contract:
When it is internal, the proxy attribute on the public base still exposes the name: azure-sdk-for-net enables ApiCompat's AttributesMustMatch rule (eng/Directory.Build.Common.targets) and does not exclude PersistableModelProxyAttribute. When the generated unknown model name differs from the shipped one, ApiCompat fails.
When it is public, renaming it is also a type removal.
The previous name generally cannot be recomputed from the current model. Shipped names usually derive from the original swagger schema name rather than the final C# base name, for example:
Base model
Generated today
Shipped (GA)
PipelineActivity
UnknownPipelineActivity
UnknownActivity
CopyActivitySource
UnknownCopyActivitySource
UnknownCopySource
DataBoxBasicJobDetails
UnknownDataBoxBasicJobDetails
UnknownJobDetails
Library authors currently restore each name by hand:
As of azure-sdk-for-net main (6d623813cb9), TypeSpec-generated libraries contain 103 such renames across 23 libraries, 94 of which are empty partials that exist only to restore the name: MachineLearning (19), DataProtectionBackup (15), RecoveryServicesBackup (14), RecoveryServicesSiteRecovery (10), DataFactory (8), DataBox (6), Cdn (5), DataMigration (4), ServiceFabricManagedClusters (4), ServiceLinker (4), Avs (2), and one each in Azure.AI.Agents.Persistent, AlertsManagement, ScVmm, BotService, CognitiveServices, CosmosDB, EdgeOrder, EventHubs, MySql, Network, Quota and StorageMover.
Proposal
When naming an unknown discriminator model, use the name recorded in the last contract's PersistableModelProxyAttribute on the corresponding base model.
The attribute is the authoritative source: it is exactly the value ApiCompat compares, it is on a public type that LastContractView already loads, and NamedTypeSymbolProvider.BuildAttributes already exposes it. This is preferred over scanning the last contract for subtypes prefixed with Unknown, which would require enumerating every type (Roslyn has no derived-type index), would need internal-type lookups in the common case where the unknown model is internal (FindForTypeInLastContract excludes internal types), and would be ambiguous for real models whose names start with Unknown and for multi-level discriminator hierarchies.
Requirements
For a model where IsUnknownDiscriminatorModel is true, read BaseModelProvider.LastContractView.Attributes, find System.ClientModel.Primitives.PersistableModelProxyAttribute, and use its typeof argument's type name as the unknown model's name.
Apply the restored name only when all of the following hold:
The base model has a last-contract view and exactly one PersistableModelProxyAttribute with a resolvable type argument.
The proxy type is in the same namespace as the current unknown model.
The name is not already used by another type the generator emits (other than this unknown model) or by a custom type that is not a customization of this unknown model.
The restoration does not reference a type whose removal is accepted in the ApiCompat baseline.
Apply per discriminated base, so each level of a multi-level hierarchy restores its own unknown model name independently.
Resolve the name when the unknown model's name is built (not by updating it afterwards), so the proxy attribute, serialization, deserialization dispatch, model factory and ModelReaderWriterContext registrations all observe the same name. The base model's name and last-contract lookup must not depend on the unknown model's name, to avoid re-entrancy.
Existing [CodeGenType("Unknown...")] customizations must continue to work unchanged, whether they target the previously generated name or the restored name.
Emit an informational back-compat diagnostic when a name is restored, and a diagnostic explaining why when a candidate name is found but rejected by one of the guards above.
When there is no last contract, or the base has no proxy attribute, behavior is unchanged.
The restoration must work whether the unknown model is internal or public. Accessibility continues to come from custom code; restoring the accessibility of an unknown model that was public in the last contract but is no longer declared public is out of scope for this issue.
Performance: at most one attribute lookup per discriminated base model; no scan of the last-contract assembly.
Success criteria
A library whose last contract has [PersistableModelProxy(typeof(UnknownActivity))] on PipelineActivity generates internal partial class UnknownActivity and [PersistableModelProxy(typeof(UnknownActivity))] with no custom code, and ApiCompat passes.
Deleting the empty CodeGenType rename partials listed above and regenerating produces no API changes and no ApiCompat errors (validate on at least DataFactory and MachineLearning).
Libraries that keep their existing CodeGenType rename partials regenerate identically.
Libraries without a last contract, and models without a last-contract proxy attribute, generate the same output as today.
Unit tests in the generator cover:
name restored from the last-contract proxy attribute;
name restored for an unknown model that custom code declares public;
multi-level discriminator hierarchy with distinct restored names per level;
restoration skipped when the name collides with another generated or custom type;
existing CodeGenType customization targeting the previously generated name still applies;
no last contract / no proxy attribute leaves the name unchanged.
This PR updates the C# client generator to restore unknown discriminator model names from the last contract’s PersistableModelProxyAttribute, reducing the need for manual compatibility customizations described in #12600.
Changes:
Restores historical names while preserving existing customizations and checking namespace, collision, and accepted-removal guards.
Reserves generated infrastructure names and reports restoration or rejection diagnostics.
Adds tests for naming, customization, hierarchy handling, collisions, and serialization references.
Paths are relative to packages/http-client-csharp/generator/.
The reason will be displayed to describe this comment to others. Learn more.
Copilot the ask was to simply respect the last contract name for unknown discriminated models. We are going out of scope by touching other code. Refactor the code to make the changes targeted to the original request described in the issue
Copilot the ask was to simply respect the last contract name for unknown discriminated models. We are going out of scope by touching other code. Refactor the code to make the changes targeted to the ...
Refactored to remove client/options/paging collision plumbing and keep historical naming focused on unknown discriminator models. Commit: 6c015a00.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved name-collision handling can overwrite generated model or enum files, create duplicate type identities, and make historical-name restoration depend on input order.
Updating this map one unknown at a time makes the collision guard at TypeFactory.cs:168-169 depend on input order: if the root's historical target is UnknownCopyActivitySource and the child's target is UnknownCopySource, root-first processing rejects the root because the child still occupies its generated name, whereas child-first processing restores both. Resolve candidate renames before checking final collisions, or revisit skipped candidates after names move, so a temporary collision does not leave the root's proxy incompatible with the last contract.
The reason will be displayed to describe this comment to others. Learn more.
Copilot we shouldn't be defining a method in this type that returns an INamedTypeSymbol. Can we not simply just return the correct back compat name within ModelProvider's BuildName method?
The reason will be displayed to describe this comment to others. Learn more.
Moved proxy-name resolution into ModelProvider.BuildName; the method now returns the historical name and no longer relies on an INamedTypeSymbol-returning helper. Commit 0a550746.
Copilot the ask was to simply respect the last contract name for unknown discriminated models. We are going out of scope by touching other code. Refactor the code to make the changes targeted to the ...
Refactored restoration into ModelProvider.BuildName and removed the separate post-processing/name-plumbing implementation. The focused naming and serialization tests pass. Commit 0a550746.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved name-resolution defects can produce duplicate generated type names and output paths, attach unrelated customizations, and miss last-contract name restorations.
The reason will be displayed to describe this comment to others. Learn more.
Copilot the changes are still way too complicated. This change should be fairly simple. When building the unknown discriminated model, we check the libraries back compat view and simply find the corresponding derived type that implements the current base model. If the names don't match, then we can assume the previous name is the name to use.
The reason will be displayed to describe this comment to others. Learn more.
The generator project does not reference System.ClientModel, so nameof(PersistableModelProxyAttribute) is unavailable there. The lookup now avoids materializing an array and reads the attribute data directly. Commit 25dde1f5.
Copilot the changes are still way too complicated. This change should be fairly simple. When building the unknown discriminated model, we check the libraries back compat view and simply find the corr...
Yes. The unknown model now lazily reads the base model’s previous PersistableModelProxyAttribute and uses its typeof target name; no derived-type scan or global name plumbing. Commit 25dde1f5.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Historical-name handling bypasses collision checks and can attach unrelated custom partials, risking conflicting declarations or overwritten model files and cache entries.
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
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.
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.