Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.openapitools.openapidiff.core.model.deferred.DeferredChanged;
import org.openapitools.openapidiff.core.model.deferred.DeferredSchemaCache;
import org.openapitools.openapidiff.core.utils.EndpointUtils;
import org.openapitools.openapidiff.core.utils.SchemaTypeNormalizer;

public class OpenApiDiff {
private PathsDiff pathsDiff;
Expand Down Expand Up @@ -103,6 +104,7 @@ public OpenApiDiffOptions getOptions() {
}

private ChangedOpenApi compare() {
normalizeCrossVersionSchemaTypes();
preProcess(oldSpecOpenApi);
preProcess(newSpecOpenApi);

Expand Down Expand Up @@ -146,6 +148,27 @@ private void setChangedExtension(ChangedExtensions changedExtension) {
this.changedExtensions = changedExtension;
}

/**
* The parser stores the OAS 3.1 {@code type} keyword in the JSON Schema 2020-12 {@code types} set
* and leaves the singular {@code type} null, while OAS 3.0 documents only use the singular {@code
* type}. When comparing across that representation boundary, mirror a single-element {@code
* types} set back into {@code type} so that identical schemas are not reported as type changes
* (see issue 858). Same-version comparisons are left untouched.
*/
private void normalizeCrossVersionSchemaTypes() {
boolean oldSpecIs31 = isOpenApi31(oldSpecOpenApi);
boolean newSpecIs31 = isOpenApi31(newSpecOpenApi);
if (oldSpecIs31 != newSpecIs31) {
SchemaTypeNormalizer.normalize(oldSpecOpenApi);
SchemaTypeNormalizer.normalize(newSpecOpenApi);
}
}

private static boolean isOpenApi31(OpenAPI openApi) {
String version = openApi.getOpenapi();
return version != null && version.startsWith("3.1");
}

private void preProcess(OpenAPI openApi) {
List<SecurityRequirement> securityRequirements = openApi.getSecurity();
if (securityRequirements != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
package org.openapitools.openapidiff.core.utils;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;

/**
* Mirrors the JSON Schema 2020-12 {@code types} set of a parsed schema back into the singular
* {@code type} keyword when it holds exactly one type.
*
* <p>For OpenAPI 3.1 documents the parser stores the {@code type} keyword in {@link
* Schema#getTypes()} and leaves {@link Schema#getType()} null, while OpenAPI 3.0 documents expose
* the same keyword only through {@link Schema#getType()}. Comparing a 3.0 document against a 3.1
* document therefore reports every identical schema as a type change (see issue 858).
*
* <p>A single-element {@code types} set and the equivalent singular {@code type} denote the same
* schema, so this normalization is lossless for those. Sets with zero or multiple types are left
* untouched because they do not correspond to any singular {@code type} value.
*/
public final class SchemaTypeNormalizer {

private SchemaTypeNormalizer() {}

/** Walks the whole document and mirrors single-element {@code types} sets into {@code type}. */
public static void normalize(OpenAPI openAPI) {
if (openAPI == null) {
return;
}
// Identity-based visited set: schemas can be shared and recursive.
Set<Object> visited = Collections.newSetFromMap(new IdentityHashMap<>());
walkPathItems(openAPI.getPaths(), visited);
walkPathItems(openAPI.getWebhooks(), visited);

Components components = openAPI.getComponents();
if (components == null) {
return;
}
walkSchemas(components.getSchemas(), visited);
if (components.getParameters() != null) {
components.getParameters().values().forEach(parameter -> walkParameter(parameter, visited));
}
if (components.getRequestBodies() != null) {
components
.getRequestBodies()
.values()
.forEach(requestBody -> walkRequestBody(requestBody, visited));
}
if (components.getResponses() != null) {
components
.getResponses()
.values()
.forEach(apiResponse -> walkApiResponse(apiResponse, visited));
}
if (components.getHeaders() != null) {
components.getHeaders().values().forEach(header -> walkSchema(header.getSchema(), visited));
}
walkPathItems(components.getPathItems(), visited);
if (components.getCallbacks() != null) {
components.getCallbacks().values().forEach(callback -> walkPathItems(callback, visited));
}
}

private static void walkPathItems(Map<String, PathItem> pathItems, Set<Object> visited) {
if (pathItems != null) {
pathItems.values().forEach(pathItem -> walkPathItem(pathItem, visited));
}
}

private static void walkPathItem(PathItem pathItem, Set<Object> visited) {
if (pathItem == null || !visited.add(pathItem)) {
return;
}
pathItem.readOperations().forEach(operation -> walkOperation(operation, visited));
}

private static void walkOperation(Operation operation, Set<Object> visited) {
if (operation == null) {
return;
}
if (operation.getParameters() != null) {
operation.getParameters().forEach(parameter -> walkParameter(parameter, visited));
}
walkRequestBody(operation.getRequestBody(), visited);
if (operation.getResponses() != null) {
operation.getResponses().values().forEach(response -> walkApiResponse(response, visited));
}
if (operation.getCallbacks() != null) {
operation.getCallbacks().values().forEach(callback -> walkPathItems(callback, visited));
}
}

private static void walkParameter(Parameter parameter, Set<Object> visited) {
if (parameter == null) {
return;
}
walkSchema(parameter.getSchema(), visited);
walkContent(parameter.getContent(), visited);
}

private static void walkRequestBody(RequestBody requestBody, Set<Object> visited) {
if (requestBody == null) {
return;
}
walkContent(requestBody.getContent(), visited);
}

private static void walkApiResponse(ApiResponse apiResponse, Set<Object> visited) {
if (apiResponse == null) {
return;
}
walkContent(apiResponse.getContent(), visited);
if (apiResponse.getHeaders() != null) {
apiResponse.getHeaders().values().forEach(header -> walkSchema(header.getSchema(), visited));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Header Objects can carry their schema under content, but this walker only visits header.getSchema(). Cross-version comparisons can therefore still report identical content-backed response or component headers as type changes; walk header.getContent() at both header call sites.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At core/src/main/java/org/openapitools/openapidiff/core/utils/SchemaTypeNormalizer.java, line 124:

<comment>Header Objects can carry their schema under `content`, but this walker only visits `header.getSchema()`. Cross-version comparisons can therefore still report identical content-backed response or component headers as type changes; walk `header.getContent()` at both header call sites.</comment>

<file context>
@@ -0,0 +1,183 @@
+    }
+    walkContent(apiResponse.getContent(), visited);
+    if (apiResponse.getHeaders() != null) {
+      apiResponse.getHeaders().values().forEach(header -> walkSchema(header.getSchema(), visited));
+    }
+  }
</file context>

}
}

private static void walkContent(Content content, Set<Object> visited) {
if (content == null) {
return;
}
for (MediaType mediaType : content.values()) {
if (mediaType != null) {
walkSchema(mediaType.getSchema(), visited);
}
}
}

private static void walkSchemas(Map<String, Schema> schemas, Set<Object> visited) {
if (schemas != null) {
schemas.values().forEach(schema -> walkSchema(schema, visited));
}
}

private static void walkSchema(Schema<?> schema, Set<Object> visited) {
if (schema == null || !visited.add(schema)) {
return;
}
normalizeType(schema);

if (schema.getProperties() != null) {
schema.getProperties().values().forEach(property -> walkSchema(property, visited));
}
walkSchema(schema.getItems(), visited);
walkSchema(schema.getNot(), visited);
walkSchema(schema.getAdditionalItems(), visited);
walkSchema(schema.getContains(), visited);
walkSchema(schema.getIf(), visited);
walkSchema(schema.getThen(), visited);
walkSchema(schema.getElse(), visited);
if (schema.getAdditionalProperties() instanceof Schema) {
walkSchema((Schema<?>) schema.getAdditionalProperties(), visited);
}
if (schema.getAllOf() != null) {
schema.getAllOf().forEach(item -> walkSchema(item, visited));
}
if (schema.getAnyOf() != null) {
schema.getAnyOf().forEach(item -> walkSchema(item, visited));
}
if (schema.getOneOf() != null) {
schema.getOneOf().forEach(item -> walkSchema(item, visited));
}
if (schema.getPrefixItems() != null) {
schema.getPrefixItems().forEach(item -> walkSchema(item, visited));
}
}

private static void normalizeType(Schema<?> schema) {
if (schema.getType() == null && schema.getTypes() != null && schema.getTypes().size() == 1) {
schema.setType(schema.getTypes().iterator().next());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: This normalization mutates caller-owned 3.1 schemas. Reusing one in a later 3.1-vs-3.1 comparison compares its populated type with a fresh parser's null, producing a false change; normalize deep copies instead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At core/src/main/java/org/openapitools/openapidiff/core/utils/SchemaTypeNormalizer.java, line 180:

<comment>This normalization mutates caller-owned 3.1 schemas. Reusing one in a later 3.1-vs-3.1 comparison compares its populated `type` with a fresh parser's `null`, producing a false change; normalize deep copies instead.</comment>

<file context>
@@ -0,0 +1,183 @@
+
+  private static void normalizeType(Schema<?> schema) {
+    if (schema.getType() == null && schema.getTypes() != null && schema.getTypes().size() == 1) {
+      schema.setType(schema.getTypes().iterator().next());
+    }
+  }
</file context>

}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.openapitools.openapidiff.core;

import static org.openapitools.openapidiff.core.TestUtils.assertOpenApiAreEquals;
import static org.openapitools.openapidiff.core.TestUtils.assertSpecUnchanged;

import org.junit.jupiter.api.Test;

/**
* The two specs are identical except for the {@code openapi} version field (3.0.1 vs 3.1.0) and
* {@code info.version}. The parser represents the same {@code type} keyword differently for the two
* versions, which used to report every operation as changed.
*/
public class Issue858Test {

private final String OAS_30_SPEC = "issue-858-1.json";
private final String OAS_31_SPEC = "issue-858-2.json";

@Test
public void testOpenApiVersionOnlyDifference30To31ReportsNoOperationChanges() {
assertOpenApiAreEquals(OAS_30_SPEC, OAS_31_SPEC);
}

@Test
public void testOpenApiVersionOnlyDifference31To30ReportsNoOperationChanges() {
assertOpenApiAreEquals(OAS_31_SPEC, OAS_30_SPEC);
}

@Test
public void testOpenApiVersionOnlyDifferenceIsUnchanged() {
assertSpecUnchanged(OAS_30_SPEC, OAS_31_SPEC);
}
}
108 changes: 108 additions & 0 deletions core/src/test/resources/issue-858-1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
{
"components": {
"schemas": {
},
"securitySchemes": {
}
},
"info": {
"description": "This is the swagger documentation for sample-api. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). ",
"title": "sample-api",
"version": "3.47.0"
},
"openapi": "3.0.1",
"paths": {
"/sample-api/export": {
"get": {
"description": "Export into MS Excel a list of Annual Accounts Versions.",
"operationId": "exportItems_1",
"parameters": [
{
"in": "query",
"name": "query",
"required": false,
"schema": {
"type": "string"
}
},
{
"in": "query",
"name": "sort",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "successful operation"
}
},
"summary": "Export list of Annual Accounts Versions in excel format",
"tags": [
"Search"
]
}
},
"/sample-api/{id}/actions/CAN": {
"post": {
"description": "Sample description",
"operationId": "cancel_1",
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"format": "int64",
"type": "integer"
}
}
],
"responses": {
"201": {
"description": "Cancel executed"
}
},
"summary": "Cancel ACA Version",
"tags": [
"ACA Workflow actions"
]
}
},
"/sample-api/{id}/actions/DEL": {
"post": {
"description": "This method should be used when a user wants to delete a ACA version from the system",
"operationId": "delete_1",
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"format": "int64",
"type": "integer"
}
}
],
"responses": {
"201": {
"description": "Delete executed"
}
},
"summary": "Delete ACA Version",
"tags": [
"ACA Workflow actions"
]
}
}
},
"security": [
],
"servers": [
{
"url": "http://sample-server"
}
]
}
Loading