Skip to content

Add ATS nullable scalar support#17153

Open
sebastienros wants to merge 2 commits into
mainfrom
sebastienros/sebros-ats-nullability
Open

Add ATS nullable scalar support#17153
sebastienros wants to merge 2 commits into
mainfrom
sebastienros/sebros-ats-nullability

Conversation

@sebastienros
Copy link
Copy Markdown
Contributor

Description

Generated polyglot SDKs currently lose C# nullable scalar property metadata, so nullable properties such as string? are emitted as non-nullable SDK types. This adds ATS type-reference nullability at member use sites and projects that metadata into generated TypeScript and Python scalar output.

The scanner now captures DTO and context property nullability with NullabilityInfoContext. TypeScript emits | null and Python emits | None for nullable primitive/enum type references, while Go, Java, and Rust behavior is intentionally unchanged. The metadata only serializes when nullable to avoid broad snapshot churn.

Related issue: N/A

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
      • If yes, did you have an API Review for it?
        • Yes
        • No
      • Did you add <remarks /> and <code /> elements on your triple slash comments?
        • Yes
        • No
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
      • If yes, have you done a threat model and had a security review?
        • Yes
        • No
    • No

sebastienros and others added 2 commits May 15, 2026 17:03
Capture nullable scalar type-reference metadata during ATS scanning and project it into generated TypeScript and Python SDK types. Add focused scanner, snapshot, and runtime tests for nullable scalar DTO and context property scenarios.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Add a concrete XML documentation example for nullable ATS type-reference metadata.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings May 16, 2026 00:05
@github-actions
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/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 17153

Or

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

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds ATS-level nullability for scalar type references captured from C# member metadata, and projects that metadata into generated TypeScript and Python SDK output so string?/int?-style members are emitted as nullable types in those languages.

Changes:

  • Extend AtsTypeRef with optional use-site nullability metadata (IsNullable) and omit it from JSON unless set.
  • Update ATS scanning to capture property nullability via NullabilityInfoContext for DTOs and exported context properties (getter/setter).
  • Update TypeScript/Python generators to emit | null / | None for nullable primitive/enum type references, and update snapshots/tests accordingly.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/Aspire.Hosting.RemoteHost.Tests/AtsCapabilityScannerTests.cs Adds coverage for DTO property nullability flowing into AtsTypeRef.IsNullable.
tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.ts Updates TS snapshot to reflect `
tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Snapshots/AtsGeneratedAspire.verified.ts Updates TS snapshot for ATS-only scan scenario to reflect nullable scalar emission.
tests/Aspire.Hosting.CodeGeneration.TypeScript.JsTests/tests/nullableProperties.test.ts Adds runtime JS test coverage for nullable scalar getter/setter behavior (null round-tripping).
tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.py Updates Python snapshot to reflect `
tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/AtsGeneratedAspire.verified.py Updates Python ATS-only snapshot to reflect `
tests/Aspire.Hosting.CodeGeneration.Python.Tests/AtsPythonCodeGeneratorTests.cs Adds targeted assertions for nullable scalar emission in generated Python.
src/Aspire.TypeSystem/AtsCapabilityInfo.cs Introduces AtsTypeRef.IsNullable (nullable scalar metadata) and adjusts JSON serialization for nullability fields.
src/Aspire.Hosting.RemoteHost/AtsCapabilityScanner.cs Uses NullabilityInfoContext to stamp use-site nullability onto DTO/context property type refs (incl. getter/setter).
src/Aspire.Hosting.CodeGeneration.TypeScript/AtsTypeScriptCodeGenerator.cs Applies `
src/Aspire.Hosting.CodeGeneration.Python/AtsPythonCodeGenerator.cs Applies `

Comment on lines +38 to +50
/// <summary>
/// Gets or sets whether this type reference accepts a JSON null value at its current use site.
/// </summary>
/// <remarks>
/// Nullability is attached to the type reference as it appears in a capability or DTO property.
/// Nested element, key, and value type nullability is only represented when those nested
/// references were scanned from member metadata that exposes nullability information.
/// For example, a DTO property declared as <code>string?</code> produces a nullable string
/// type reference, while the same CLR <see cref="string" /> type on a non-nullable property does not.
/// </remarks>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool? IsNullable { get; init; }

Comment on lines +304 to +309
Assert.Contains("OptionalField: str | None", aspirePy);
Assert.Contains("def description(self) -> str | None:", aspirePy);
Assert.Contains("def description(self, value: str | None) -> None:", aspirePy);
Assert.Contains("Name: str", aspirePy);
Assert.Contains("def name(self) -> str:", aspirePy);
Assert.Contains("def name(self, value: str) -> None:", aspirePy);
@github-actions
Copy link
Copy Markdown
Contributor

🎬 CLI E2E Test Recordings — 85 recordings uploaded (commit 2043e71)

View all recordings
Status Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View Recording
AddPackageWhileAppHostRunningDetached ▶️ View Recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View Recording
AgentInitCommand_DefaultSelection_InstallsSkillOnly ▶️ View Recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View Recording
AspireAddPackageVersionToDirectoryPackagesProps ▶️ View Recording
AspireInitSingleFileAppHostRunsViaDotnetRunAppHost ▶️ View Recording
AspireInitWithExistingAppHostDirRecreatesMissingNuGetConfigAndPreservesFiles ▶️ View Recording
AspireInitWithSolutionFileGeneratesAppHostThatBuildsAgainstChannelHive ▶️ View Recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ View Recording
AspireUpdateRemovesOrphanAppHostPackageVersionWhenSdkAlreadyCurrent ▶️ View Recording
Banner_DisplayedOnFirstRun ▶️ View Recording
Banner_DisplayedWithExplicitFlag ▶️ View Recording
Banner_NotDisplayedWithNoLogoFlag ▶️ View Recording
CertificatesClean_RemovesCertificates ▶️ View Recording
CertificatesTrust_WithNoCert_CreatesAndTrustsCertificate ▶️ View Recording
CertificatesTrust_WithUntrustedCert_TrustsCertificate ▶️ View Recording
ConfigSetGet_CreatesNestedJsonFormat ▶️ View Recording
CreateAndRunAspireStarterProject ▶️ View Recording
CreateAndRunAspireStarterProjectWithBundle ▶️ View Recording
CreateAndRunEmptyAppHostProject ▶️ View Recording
CreateAndRunJavaEmptyAppHostProject ▶️ View Recording
CreateAndRunJsReactProject ▶️ View Recording
CreateAndRunPythonReactProject ▶️ View Recording
CreateAndRunTypeScriptEmptyAppHostProject ▶️ View Recording
CreateAndRunTypeScriptStarterProject ▶️ View Recording
CreateJavaAppHostWithViteApp ▶️ View Recording
CreateTypeScriptAppHostWithViteApp_UsesConfiguredToolchain ▶️ View Recording
DashboardRunWithOtelTracesReturnsNoTraces ▶️ View Recording
DeployK8sBasicApiService ▶️ View Recording
DeployK8sWithExternalHelmChart ▶️ View Recording
DeployK8sWithGarnet ▶️ View Recording
DeployK8sWithMongoDB ▶️ View Recording
DeployK8sWithMySql ▶️ View Recording
DeployK8sWithPostgres ▶️ View Recording
DeployK8sWithRabbitMQ ▶️ View Recording
DeployK8sWithRedis ▶️ View Recording
DeployK8sWithSqlServer ▶️ View Recording
DeployK8sWithValkey ▶️ View Recording
DeployTypeScriptAppToKubernetes ▶️ View Recording
DescribeCommandResolvesReplicaNames ▶️ View Recording
DescribeCommandShowsRunningResources ▶️ View Recording
DetachFormatJsonProducesValidJson ▶️ View Recording
DetachFormatJsonProducesValidJsonWhenRestartingExistingInstance ▶️ View Recording
DoListStepsShowsPipelineSteps ▶️ View Recording
DocsCommand_RendersInteractiveMarkdownFromLocalSource ▶️ View Recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ View Recording
DoctorCommand_TypeScriptAppHostReportsMissingConfiguredToolchain ▶️ View Recording
DoctorCommand_WithSslCertDir_ShowsTrusted ▶️ View Recording
DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted ▶️ View Recording
GlobalMigration_HandlesCommentsAndTrailingCommas ▶️ View Recording
GlobalMigration_HandlesMalformedLegacyJson ▶️ View Recording
GlobalMigration_PreservesAllValueTypes ▶️ View Recording
GlobalMigration_SkipsWhenNewConfigExists ▶️ View Recording
GlobalSettings_MigratedFromLegacyFormat ▶️ View Recording
InitTypeScriptAppHost_AugmentsExistingViteRepoAtRoot ▶️ View Recording
InteractiveCSharpInitCreatesExpectedFiles ▶️ View Recording
InvalidAppHostPathWithComments_IsHealedOnRun ▶️ View Recording
LatestCliCanStartStableChannelAppHost ▶️ View Recording
LatestCliCanStartStableChannelTypeScriptAppHost ▶️ View Recording
LegacySettingsMigration_AdjustsRelativeAppHostPath ▶️ View Recording
LogLevelTrace_ProducesTraceEntriesInCliLogFile ▶️ View Recording
LogsCommandShowsResourceLogs ▶️ View Recording
OtelLogsReturnsStructuredLogsFromStarterAppCore ▶️ View Recording
PsCommandListsRunningAppHost ▶️ View Recording
PsFormatJsonOutputsOnlyJsonToStdout ▶️ View Recording
PublishWithConfigureEnvFileUpdatesEnvOutput ▶️ View Recording
PublishWithDockerComposeServiceCallbackSucceeds ▶️ View Recording
PublishWithoutOutputPathUsesAppHostDirectoryDefault ▶️ View Recording
ResourceCommand_FailsWhenInteractionServiceIsRequired ▶️ View Recording
ResourceCommand_SetAndDeleteParameterUpdatesDescribeOutput ▶️ View Recording
RestoreGeneratesSdkFiles ▶️ View Recording
RestoreGeneratesSdkFiles_WithConfiguredToolchain ▶️ View Recording
RestoreRefreshesGeneratedSdkAfterAddingIntegration ▶️ View Recording
RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes ▶️ View Recording
RunFromParentDirectory_UsesExistingConfigNearAppHost ▶️ View Recording
SecretCrudOnDotNetAppHost ▶️ View Recording
SecretCrudOnTypeScriptAppHost ▶️ View Recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ▶️ View Recording
StartAndWaitForTypeScriptSqlServerAppHostWithNativeAssets ▶️ View Recording
StopAllAppHostsFromAppHostDirectory ▶️ View Recording
StopNonInteractiveSingleAppHost ▶️ View Recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View Recording
UnAwaitedChainsCompileWithAutoResolvePromises ▶️ View Recording
UpdateProjectChannelToStable_TypeScript_PicksUpStablePackages ▶️ View Recording

📹 Recordings uploaded automatically from CI run #25947285922

Copy link
Copy Markdown
Member

@JamesNK JamesNK left a comment

Choose a reason for hiding this comment

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

LGTM — clean implementation of nullable scalar metadata propagation through the ATS pipeline. Two minor comments: (1) unused NullableScalarContext test type that could have a companion scanner test, (2) serialization behavior change on existing AtsParameterInfo.IsNullable. Neither is blocking.

}

[AspireExport(ExposeProperties = true)]
private sealed class NullableScalarContext
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NullableScalarContext is defined here with [AspireExport(ExposeProperties = true)] but no test validates its scanned capabilities. ScanAssembly_DtoNullableScalarProperties_SetTypeRefNullability only covers NullableScalarDto. The context property scanning path (CreateContextTypeCapabilities) has its own WithNullability calls for getter/setter type refs — consider adding a companion test that validates the getter returns a nullable AtsTypeRef and the setter's value parameter has IsNullable == true.

The feature is covered by snapshot tests via TestCallbackContext/TestEnvironmentContext, so this is a test robustness gap rather than a correctness issue.

/// <summary>
/// Gets or sets whether this parameter is nullable.
/// </summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Adding [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] to this pre-existing bool property changes the wire format: "isNullable": false was previously emitted and will now be omitted. Consumers that treat a missing field as its default (false) are unaffected, but any consumer doing explicit presence-checking on the JSON key could break. Worth confirming no downstream consumer relies on the explicit presence of this field.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants