Repository navigation
Description
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
While playing around hacking SchemaReferenceTransformers I got an itch around OpenApiDocumentExtensions.AddOpenApiSchemaByReference:
document.Workspace ??= new();
var location = document.BaseUri + "/components/schemas/" + schemaId;
document.Workspace.RegisterComponentForDocument(document, schema, location);So when debugging some unit tests I found that schemas are added twice. For OpenApiSchemaServiceTests.GetOpenApiRequestBody_GeneratesSchemaForPoco it adds the Todo schema 2 times:
https://openapi.net/d6bd3466-1e30-4009-a52a-c5e42c50c184#/components/schemas/https://openapi.net/d6bd3466-1e30-4009-a52a-c5e42c50c184/components/schemas/Todohttps://openapi.net/d6bd3466-1e30-4009-a52a-c5e42c50c184#/components/schemas/Todo
The first is added in the OpenApiDocumentExtensions.AddOpenApiSchemaByReference method. The second is added in the OpenApiDocumentService.GetOpenApiDocumentAsync (document.Workspace.RegisterComponents(document)). This last one scans all components and adds them to the workspace (so they are correct from a OpenAPI.NET point of view).
I tried changing OpenApiDocumentExtensions.AddOpenApiSchemaByReference to one of the following:
document.Workspace.RegisterComponentForDocument(document, schema, schemaId);document.AddComponent(schemaId, schema);
Both add the schema as expected to the workspace but it fails some tests caused by circular references. This is because the moment they are added correctly to the workspace they are used when resolving references. The way how RegisterComponent works is different than just assigning the schema in document.Components.Schemas[schemaId] = schema;. RegisterComponent does not overwrite a component (TryAdd), but assigning does.
Related method:
public static IOpenApiSchema AddOpenApiSchemaByReference(this OpenApiDocument document, string schemaId, IOpenApiSchema schema)
{
if(schema is OpenApiSchemaReference)
{
throw new ArgumentException("Schema is already a reference.", nameof(schema));
}
document.Components ??= new();
document.Components.Schemas ??= new Dictionary<string, IOpenApiSchema>();
document.Components.Schemas[schemaId] = schema;
document.Workspace ??= new();
var location = document.BaseUri + "/components/schemas/" + schemaId;
document.Workspace.RegisterComponentForDocument(document, schema, location);
object? description = null;
object? example = null;
if (schema is OpenApiSchema actualSchema)
{
actualSchema.Metadata?.TryGetValue(OpenApiConstants.RefDescriptionAnnotation, out description);
actualSchema.Metadata?.TryGetValue(OpenApiConstants.RefExampleAnnotation, out example);
}
return new OpenApiSchemaReference(schemaId, document)
{
Description = description as string,
Examples = example is JsonNode exampleJson ? [exampleJson] : null,
};
}My proposed fix is to remove the whole part around the workspace in AddOpenApiSchemaByReference as it's not used anyway for resolving references. In the OpenApiDocumentService we still keep the initialization of the workspaces which gives is a correctly initialized workspace.
The below passes all tests:
public static IOpenApiSchema AddOpenApiSchemaByReference(this OpenApiDocument document, string schemaId, IOpenApiSchema schema)
{
if(schema is OpenApiSchemaReference)
{
throw new ArgumentException("Schema is already a reference.", nameof(schema));
}
document.Components ??= new();
document.Components.Schemas ??= new Dictionary<string, IOpenApiSchema>();
document.Components.Schemas[schemaId] = schema;
object? description = null;
object? example = null;
if (schema is OpenApiSchema actualSchema)
{
actualSchema.Metadata?.TryGetValue(OpenApiConstants.RefDescriptionAnnotation, out description);
actualSchema.Metadata?.TryGetValue(OpenApiConstants.RefExampleAnnotation, out example);
}
return new OpenApiSchemaReference(schemaId, document)
{
Description = description as string,
Examples = example is JsonNode exampleJson ? [exampleJson] : null,
};
}Another fix could be just removing the initialization of the Workspace completly as it's not required for the functionality.
@captainsafia let me know what you think 😊. I can make the change, I just don't know where you would like the unit tests for the Workspace initialization (as there are none right now).
Expected Behavior
No response
Steps To Reproduce
No response
Exceptions (if any)
No response
.NET Version
10.0.100-rc.1.25420.111
Anything else?
It's not a breaking bug.
Activity
MihuBot commentedon Sep 9, 2025
I'm a bot. Here are possible related and/or duplicate issues (I may be wrong):
captainsafia commentedon Sep 9, 2025
Did you validate this? At some point in the previews, the library (Microsoft.OpenApi, here) did require you to initialize the workspace otherwise some refs would fail to resolve. There is a chance that this constraint was relaxed at some point and the change wasn't captured in any of the release notes.
desjoerd commentedon Sep 9, 2025
I will put in a draft PR (I think this runs the CI as well) which removes it from the
AddOpenApiSchemaByReference. Than we can think of a next action or adding unit tests.I did verify it by removing it at that point and run all unit tests on
main. I was surprised as well.Removing the workspace resulted in the current existing behavior, when I updated it to be added without the prefix some unit tests started failing. My reasoning behind that is because when they are added with only the schema Id the workspace actually resolves them and because it's a TryAdd it doesn't overwrite it while being in the recursive ResolveReferences.
desjoerd commentedon Sep 9, 2025
@captainsafia I've created a draft PR #63606.
I think it has been probably relaxed and there has been logic added for resolving references based on the document itself. AND there probably has a change around the component registration location requiring a
#to be a treated as a relative reference.GetOrCreateSchemaAsyncwith inner references #64252 as a duplicate of this issuelauraneto commentedon Nov 6, 2025
This issue is causing my document generation to fail completely with
InvalidOperationException: The input schema must be an OpenApiSchema or OpenApiSchemaReference., because it tries to retrieve references fromOpenApiWorkspace._IOpenApiReferenceableRegistrybut the ids don't match (due to the duplicate base location).You can find more details in the issue I had created and now marked as duplicate: #64252.
I wasn't able to reproduce this using minimal reproduction steps, but I have since seen that it might be related to me manually configuring
oneOf, and then it trying to retrieve inner references of that referenced schema. (when I comment out theoneOf, the document is generated without errors)desjoerd commentedon Nov 6, 2025
I think it's actually an ordering issue, as retrieving schemas from the document has a fallback into resolving the actual "$ref" (otherwise almost everything would be broken, and it's why this issue wasn't found).
It could be that #64109 solves the issue as it fixes some ordering issues (not all).
But I think you're having a different issue. @lauraneto could you share the stacktrace? Was this thrown in your own Transformer or was this coming from the aspnetcore implementation (eg
ResolveReferenceForSchema).lauraneto commentedon Nov 6, 2025
Here is the stacktrace:
So it doesn't seem to be thrown in the transformer itself, but after.
desjoerd commentedon Nov 6, 2025
Ok, now I think, I should've asked for the transformer logic as well 😅.
So the flow is as follows:
a. Create full schema from JsonSchemaExporter (with some transformations, that is, assigning schema id's)
b. Map to OpenApiSchema (fully resolved/nested schemas)
c. Run SchemaTransformers for the full structure
Recursive function, moving everything which should've been a reference into components and changing it to a reference.
It will start with unwrapping the schema for when the JsonSchemaExporter decided to generate a schemareference. Then it will move every schema with a
x-schema-idinto acomponentand replace it with a reference. Last one wins with .NET 10 RC2, if #64109 get's merged, the first one wins. It will continue doing this recursively for the whole tree.My hunch is, you insert a IOpenAPIReference within a schema transformer to a schema which is being added with a DocumentTransformer. Or to a schema which is being added with
OpenApiSchemaTransformerContext.GetOrCreateSchemaAsync.Could you share what you're doing within the Transformer (around the OneOf), or maybe some other customizations. I think we could create a repro.
desjoerd commentedon Nov 7, 2025
@lauraneto I was wrong, by chance I've hit the same issue. The $ref resolving fallback is only for sub schemas 😔.
I think #64109 will actually fix this 😊. Now trying to get to a minimal repro showing the root cause so it can be added as a unit test.
From what I see, it happens when a "resolved" schema get's assigned (on a new property for example, or oneOf) within a transformer. Resolved meaning, all nested schemas are resolved into schemas and schema references.
For me it happened when I was caching a schema from
context.GetOrCreateSchemaAsyncand used it to map these onto the transformed schema. This is an "Unresolved schema", but when I apply it a second time with the cached value, it could be, that it became "Resolved", e.g. all schemas with "x-schema-id" replaced with references.Background:
I wanted to cache it because in the current version it will emit a schema which will become a reference using the unsupported
x-schema-id(I don't expect this to work in the future as it's unsupported). But that causes a problem where if the schema is reused, the last schema wins, so that is the "empty" schema which becomes a reference, this overwrites the created schema ofcontext.GetOrCreateSchemaAsync. I needed to do these extra checks, because of #64266.(https://github.com/desjoerd/OptionalValues/blob/369b4a2d2322bb9fd052967b08d3799441728fb7/src/OptionalValues.OpenApi/OptionalValuesSchemaTransformer.cs)