Skip to content

OpenAPI: document.Workspace has schemas duplicated #63598

Closed

Description

@desjoerd

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:

  1. https://openapi.net/d6bd3466-1e30-4009-a52a-c5e42c50c184#/components/schemas/https://openapi.net/d6bd3466-1e30-4009-a52a-c5e42c50c184/components/schemas/Todo
  2. https://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

  1. added
    needs-area-label
    on Sep 9, 2025
  2. added
    area-minimal
    and removed
    needs-area-label
    on Sep 9, 2025
  3. added this to the Backlog milestone on Sep 9, 2025
  4. captainsafia commented on Sep 9, 2025

    @captainsafia
    Contributor

    Another fix could be just removing the initialization of the Workspace completly as it's not required for the functionality.

    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.

  5. desjoerd commented on Sep 9, 2025

    @desjoerd
    ContributorAuthor

    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.

  6. desjoerd commented on Sep 9, 2025

    @desjoerd
    ContributorAuthor

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

  7. lauraneto commented on Nov 6, 2025

    @lauraneto

    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 from OpenApiWorkspace._IOpenApiReferenceableRegistry but 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 the oneOf, the document is generated without errors)

  8. desjoerd commented on Nov 6, 2025

    @desjoerd
    ContributorAuthor

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

  9. lauraneto commented on Nov 6, 2025

    @lauraneto

    Here is the stacktrace:

    System.InvalidOperationException: The input schema must be an OpenApiSchema or OpenApiSchemaReference.
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.UnwrapOpenApiSchema(IOpenApiSchema sourceSchema)
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveReferenceForSchema(OpenApiDocument document, IOpenApiSchema inputSchema, String rootSchemaId, String baseSchemaId)
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveReferenceForSchema(OpenApiDocument document, IOpenApiSchema inputSchema, String rootSchemaId, String baseSchemaId)
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveReferenceForSchema(OpenApiDocument document, IOpenApiSchema inputSchema, String rootSchemaId, String baseSchemaId)
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveReferenceForSchema(OpenApiDocument document, IOpenApiSchema inputSchema, String rootSchemaId, String baseSchemaId)
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.ResolveReferenceForSchema(OpenApiDocument document, IOpenApiSchema inputSchema, String rootSchemaId, String baseSchemaId)
       at Microsoft.AspNetCore.OpenApi.OpenApiSchemaService.GetOrCreateSchemaAsync(OpenApiDocument document, Type type, IServiceProvider scopedServiceProvider, IOpenApiSchemaTransformer[] schemaTransformers, ApiParameterDescription parameterDescription, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetJsonRequestBody(OpenApiDocument document, IList`1 supportedRequestFormats, ApiParameterDescription bodyParameter, IServiceProvider scopedServiceProvider, IOpenApiSchemaTransformer[] schemaTransformers, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetRequestBodyAsync(OpenApiDocument document, ApiDescription description, IServiceProvider scopedServiceProvider, IOpenApiSchemaTransformer[] schemaTransformers, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetOperationAsync(ApiDescription description, OpenApiDocument document, IServiceProvider scopedServiceProvider, IOpenApiSchemaTransformer[] schemaTransformers, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetOperationsAsync(IGrouping`2 descriptions, OpenApiDocument document, IServiceProvider scopedServiceProvider, IOpenApiOperationTransformer[] operationTransformers, IOpenApiSchemaTransformer[] schemaTransformers, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetOpenApiPathsAsync(OpenApiDocument document, IServiceProvider scopedServiceProvider, IOpenApiOperationTransformer[] operationTransformers, IOpenApiSchemaTransformer[] schemaTransformers, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.OpenApi.OpenApiDocumentService.GetOpenApiDocumentAsync(IServiceProvider scopedServiceProvider, HttpRequest httpRequest, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.<>c__DisplayClass0_0.<<MapOpenApi>b__0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Http.Generated.<GeneratedRouteBuilderExtensions_g>F0399B8B15BE443123F4BECEE84B112C1912EE3F44D9DDD7BFA38E371FB917343__GeneratedRouteBuilderExtensionsCore.<>c__DisplayClass2_0.<<MapGet0>g__RequestHandler|5>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    

    So it doesn't seem to be thrown in the transformer itself, but after.

  10. desjoerd commented on Nov 6, 2025

    @desjoerd
    ContributorAuthor

    Ok, now I think, I should've asked for the transformer logic as well 😅.

    So the flow is as follows:

    1. GetJsonRequestBody
    2. GetOrCreateSchemaAsync
      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
    3. ResolveReferences
      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-id into a component and 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.

  11. desjoerd commented on Nov 7, 2025

    @desjoerd
    ContributorAuthor

    @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.GetOrCreateSchemaAsync and 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 of context.GetOrCreateSchemaAsync. I needed to do these extra checks, because of #64266.

    (https://github.com/desjoerd/OptionalValues/blob/369b4a2d2322bb9fd052967b08d3799441728fb7/src/OptionalValues.OpenApi/OptionalValuesSchemaTransformer.cs)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalfeature-openapi

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions