Skip to content

[WIP] Fix LastContractView to restore previous names of unknown discriminator models - #12601

Draft
Jorge Rangel (jorgerangel-msft) wants to merge 10 commits into
mainfrom
copilot/lastcontractview-restore-previous-names
Draft

Jorge Rangel (jorgerangel-msft) wants to merge 10 commits into
mainfrom
copilot/lastcontractview-restore-previous-names

Conversation

@jorgerangel-msft

Copy link
Copy Markdown
Contributor

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:

[CodeGenType("UnknownPipelineActivity")]
internal partial class UnknownActivity
{
}

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

  1. 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.
  2. 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.
  3. Apply per discriminated base, so each level of a multi-level hierarchy restores its own unknown model name independently.
  4. 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.
  5. Existing [CodeGenType("Unknown...")] customizations must continue to work unchanged, whether they target the previously generated name or the restored name.
  6. 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.
  7. When there is no last contract, or the base has no proxy attribute, behavior is unchanged.
  8. 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.
  9. 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.

Parent: #7241

Checklist

Comments on the Issue (you are Copilot in this section)

…st contract

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
@microsoft-github-policy-service microsoft-github-policy-service Bot added the emitter:client:csharp Issue for the C# client emitter: @typespec/http-client-csharp label Nov 17, 2026
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
@pkg-pr-new

pkg-pr-new Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@typespec/http-client-csharp@12601

commit: 25dde1f

@github-actions

Copy link
Copy Markdown
Contributor

No changes needing a change description found.

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

Unknown-model collision checks depend on input order and can reject valid mapped names, retaining incorrect names and causing ApiCompat failures.

1 open issue
What changed in this PR

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/.

File Description
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNameRestored(LastContract)/​Models.cs Historical proxy and invalid-attribute fixtures.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNamePreservesCustomization(Restored)/​UnknownActivity.cs Customization targeting the restored name.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNamePreservesCustomization(LegacyPublic)/​UnknownActivity.cs Public customization targeting the legacy name.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNamePreservesCustomization(LegacyInternal)/​UnknownActivity.cs Internal customization targeting the legacy name.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNamePreservesCustomization(Direct)/​UnknownActivity.cs Direct partial-class customization fixture.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNameCollisionSkipped(UnrelatedMapping)/​UnknownActivity.cs Unrelated customization mapping fixture.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNameCollisionSkipped(MovedCustomization)/​UnknownActivity.cs Cross-namespace customization fixture.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNameCollisionSkipped(MappedModel)/​UnknownActivity.cs Mapped generated-model collision fixture.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​TestData/​ModelProviderTests/​UnknownDiscriminatorNameCollisionSkipped(Custom)/​UnknownActivity.cs Non-partial custom-type collision fixture.
Microsoft.TypeSpec.Generator/​test/​Providers/​ModelProviders/​ModelProviderTests.cs Tests restoration, customizations, hierarchies, and rejection guards.
Microsoft.TypeSpec.Generator/​src/​TypeFactory.cs Resolves historical names and checks reserved names.
Microsoft.TypeSpec.Generator/​src/​SourceInput/​SourceInputModel.cs Identifies compatible customizations.
Microsoft.TypeSpec.Generator/​src/​Providers/​TypeProvider.cs Exposes names for collision checks.
Microsoft.TypeSpec.Generator/​src/​Providers/​ModelProvider.cs Reads historical proxy types and preserves legacy customization lookup.
Microsoft.TypeSpec.Generator/​src/​EmitterRpc/​Emitter.cs Adds diagnostic display labels.
Microsoft.TypeSpec.Generator/​src/​EmitterRpc/​BackCompatibilityChangeCategory.cs Defines restoration and rejection diagnostic categories.
Microsoft.TypeSpec.Generator.ClientModel/​test/​Providers/​MrwSerializationTypeDefinitions/​TestData/​DiscriminatorTests/​HistoricalUnknownNameUsedBySerialization/​Models.cs Historical contract fixture for serialization tests.
Microsoft.TypeSpec.Generator.ClientModel/​test/​Providers/​MrwSerializationTypeDefinitions/​TestData/​DiscriminatorTests/​HistoricalUnknownNameUsedBySerialization(Public)/​UnknownActivity.cs Public fallback-model customization fixture.
Microsoft.TypeSpec.Generator.ClientModel/​test/​Providers/​MrwSerializationTypeDefinitions/​TestData/​DiscriminatorTests/​HistoricalUnknownNameUsedBySerialization.cs Expected restored proxy attribute.
Microsoft.TypeSpec.Generator.ClientModel/​test/​Providers/​MrwSerializationTypeDefinitions/​TestData/​DiscriminatorTests/​HistoricalUnknownNameDoesNotCollideWithInfrastructure/​Models.cs Infrastructure and paging collision fixtures.
Microsoft.TypeSpec.Generator.ClientModel/​test/​Providers/​MrwSerializationTypeDefinitions/​DiscriminatorTests.cs Tests serialization references and infrastructure collisions.
Microsoft.TypeSpec.Generator.ClientModel/​src/​ScmTypeFactory.cs Reserves client infrastructure and paging helper names.
Microsoft.TypeSpec.Generator.ClientModel/​src/​Providers/​CollectionResultDefinition.cs Extracts reusable paging collection naming logic.
Microsoft.TypeSpec.Generator.ClientModel/​src/​Providers/​ClientProvider.cs Supplies operation-name candidates for collision checks.
Microsoft.TypeSpec.Generator.ClientModel/​src/​Providers/​ClientOptionsProvider.cs Extracts reusable client-options naming logic.

Review effort: Balanced

…ly of input order

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

Copilot AI commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

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.

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

Unresolved name-collision handling can overwrite generated model or enum files, create duplicate type identities, and make historical-name restoration depend on input order.

3 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Resolve candidate renames before checking final collisions

packages/​http-client-csharp/​generator/​Microsoft.TypeSpec.Generator/​src/​TypeFactory.cs:194

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.

Review effort: Balanced

Comment on lines +132 to +134
var emittedTypes = candidates.ToDictionary(
pair => pair.Key,
pair => (pair.Value.FinalName == pair.Value.Name ? result[pair.Key] : pair.Value.FinalName, pair.Value.FinalNamespace));
Comment on lines +168 to +169
else if (emittedTypes.Any(pair => pair.Key != model && pair.Value == (finalName, finalNamespace)) ||
reservedTypes.Contains((finalName, finalNamespace)))
: BuildNameWithoutCollisionCheck();
}

internal INamedTypeSymbol? GetLastContractProxyType(string typeName, string typeNamespace)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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?

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.

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.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

Copilot AI commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

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.

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

Unresolved name-resolution defects can produce duplicate generated type names and output paths, attach unrelated customizations, and miss last-contract name restorations.

6 open issues
1 resolved since last review

Review effort: Balanced

Comment on lines +121 to +122
result.Add(model, candidate.DefaultName);
continue;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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.


var attributes = lastContractBase.Attributes
.Where(attribute => attribute.Data?.AttributeClass?.ToDisplayString() ==
"System.ClientModel.Primitives.PersistableModelProxyAttribute").ToArray();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Copilot can we use nameof(PersistableModelProxyAttribute) here ? In addition, can we avoid constructing the array if there are no elements?

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Copilot in that case, this should go in scmmodelprovider, not ModelProvider

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

Copilot AI commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

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.

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.

Comment on lines +447 to +449
if (IsUnknownDiscriminatorModel && _lastContractUnknownDiscriminatorModelName.Value is { } historicalName)
{
return historicalName;
Comment on lines +490 to +491
if (proxyAttribute.ConstructorArguments is not
[{ Kind: TypedConstantKind.Type, Value: INamedTypeSymbol { TypeKind: not TypeKind.Error } proxyType }])
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

emitter:client:csharp Issue for the C# client emitter: @typespec/http-client-csharp

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LastContractView - Restore Previous Names of Unknown Discriminator Models

3 participants