From a0e6e4942cf80750261dfbac59c3c61500519351 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 23 Nov 2026 15:14:42 +0100 Subject: [PATCH 01/11] fix(what-changed): keep the response use of schemas in exclusive unions A oneOf accepts an instance only when exactly one branch matches, so the usage walk treated every branch as used by both requests and responses. A required entry added to a schema that only responses use stayed breaking whenever the schema sat in a oneOf. Branches that cannot match the same instance, because their types are disjoint or because there is a single branch, cannot interfere with each other, so they now keep the direction of the oneOf, as anyOf does. Branches that overlap, that do not state a type, or that mix integer and number keep the shared result. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 95 ++++++++++++++- what-changed/model/schema_usage_oneof_test.go | 111 ++++++++++++++++++ what-changed/model/schema_usage_test.go | 2 +- 3 files changed, 206 insertions(+), 2 deletions(-) create mode 100644 what-changed/model/schema_usage_oneof_test.go diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 1d48e6b1..3da3c874 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -264,7 +264,13 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc case v3.NotLabel, v3.IfLabel, v3.ContainsLabel: w.walk(value, schemaObject, sharedSchema) case v3.OneOfLabel: - w.each(value, schemaObject, sharedSchema) + // An exclusive union rejects an instance that matches two branches, so a branch that gains data can make + // a second one match. Branches that cannot match the same instance cannot interfere, as with anyOf. + if w.exclusiveBranches(value) { + w.each(value, schemaObject, sameInstance) + } else { + w.each(value, schemaObject, sharedSchema) + } case v3.SchemaDialectLabel: if !knownUsageDialect(value) { w.unknown = true @@ -275,6 +281,93 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc } } +// exclusiveBranches reports whether no instance can match two of the branches, so that exclusivity does not depend +// on what a branch contains. That holds for a single branch and for branches that accept different types. +func (w *usageWalker) exclusiveBranches(branches *yaml.Node) bool { + branches = utils.NodeAlias(branches) + if branches.Kind != yaml.SequenceNode { + return false + } + if len(branches.Content) == 1 { + return true + } + seen := make(map[string]bool) + for _, branch := range branches.Content { + types, ok := w.instanceTypes(branch) + if !ok { + return false + } + for _, t := range types { + if seen[t] { + return false + } + seen[t] = true + } + } + return true +} + +// instanceTypes lists the JSON types a schema can accept, following local references. Any other keyword can only +// narrow that list, so it is a safe upper bound. It reports false when the schema does not state its type. +func (w *usageWalker) instanceTypes(node *yaml.Node) ([]string, bool) { + const maxReferenceDepth = 8 + for range maxReferenceDepth { + node = utils.NodeAlias(node) + if node.Kind != yaml.MappingNode { + return nil, false + } + var declared *yaml.Node + var ref string + nullable := false + for key, value := range usageFields(node) { + switch key { + case v3.TypeLabel: + declared = utils.NodeAlias(value) + case v3.RefLabel: + ref = utils.NodeAlias(value).Value + case "nullable": + nullable = utils.NodeAlias(value).Value == "true" + } + } + if declared == nil { + if ref == "" { + return nil, false + } + if node = w.localTarget(ref); node == nil { + return nil, false + } + continue + } + var names []string + switch declared.Kind { + case yaml.ScalarNode: + names = []string{declared.Value} + case yaml.SequenceNode: + for _, item := range declared.Content { + if utils.NodeAlias(item).Kind != yaml.ScalarNode { + return nil, false + } + names = append(names, utils.NodeAlias(item).Value) + } + default: + return nil, false + } + if nullable { + names = append(names, "null") + } + var types []string + for _, name := range names { + types = append(types, name) + // Every integer is a number, so the two overlap. + if name == "number" { + types = append(types, "integer") + } + } + return types, len(types) > 0 + } + return nil, false +} + // Other dialects may introduce applicators that the OpenAPI schema walk cannot follow. func knownUsageDialect(value *yaml.Node) bool { switch strings.TrimSuffix(utils.NodeAlias(value).Value, "#") { diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go new file mode 100644 index 00000000..0fcc2bf2 --- /dev/null +++ b/what-changed/model/schema_usage_oneof_test.go @@ -0,0 +1,111 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package model + +import ( + "context" + "strings" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/index" + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +func TestRequiredOneOfBranches(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + const extra = ` + List: {type: array, items: {$ref: '#/components/schemas/Widget'}} + Page: {type: object, properties: {item: {$ref: '#/components/schemas/Widget'}}}` + for _, tc := range []struct { + name, schema string + breaking bool + }{ + {"single branch", "oneOf: [" + widget + "]", false}, + {"array or object", "oneOf: [{type: array, items: " + widget + "}, {type: object, properties: {widgets: {type: array, items: " + widget + "}}}]", false}, + {"branches by reference", "oneOf: [{$ref: '#/components/schemas/List'}, {$ref: '#/components/schemas/Page'}]", false}, + {"null or object", "oneOf: [{type: 'null'}, " + widget + "]", false}, + {"list of types", "oneOf: [{type: [string, number]}, {type: [array, 'null'], items: " + widget + "}]", false}, + {"two objects", "oneOf: [" + widget + ", {type: object, required: [other], properties: {other: {type: string}}}]", true}, + {"two arrays", "oneOf: [{type: array, items: " + widget + "}, {type: array, items: {type: string}}]", true}, + {"integer and number", "oneOf: [{type: integer}, {type: number}, " + widget + "]", true}, + {"branch without a type", "oneOf: [" + widget + ", {properties: {other: {type: string}}}]", true}, + {"boolean branch", "oneOf: [" + widget + ", true]", true}, + {"nullable branches", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: true}]", true}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) + schemas := func(required string) string { + return usageWidget(required) + extra + } + requireEntryBreaking(t, usageSpec(op, schemas("name")), usageSpec(op, schemas("name, id")), tc.breaking) + }) + } +} + +func TestRequiredOneOfBranchesKeepTheirDirection(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + union := "oneOf: [{type: array, items: " + widget + "}, {type: object, properties: {widgets: {type: array, items: " + widget + "}}}]" + // The same union in a request makes the schema shared with the response, so it must stay breaking. + op := strings.Replace(usageShared, widget, "{"+union+"}", 1) + requireEntryBreaking(t, usageSpec(op, usageWidget("name")), usageSpec(op, usageWidget("name, id")), true) + // A removed requirement is only safe for a request, so a union used by a response alone must stay breaking. + op = strings.Replace(usageResponseOnly, widget, "{"+union+"}", 1) + requireEntryBreaking(t, usageSpec(op, usageWidget("name, id")), usageSpec(op, usageWidget("name")), true) +} + +// widgetUsage returns the direction of Widget in a document whose only response schema is the given YAML. The second +// result is false when the usage of the document is unknown. +func widgetUsage(t *testing.T, schema string) (schemaDirection, bool) { + t.Helper() + spec := `openapi: 3.1.0 +info: {title: Direction, version: 1.0.0} +paths: + /widgets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: ` + schema + ` +components: + schemas: + Widget: {type: object} + Loop: {$ref: '#/components/schemas/Loop'}` + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(spec), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + usage := buildSchemaUsage(idx) + if usage == nil { + return 0, false + } + widget := idx.FindComponentInRoot(context.Background(), "#/components/schemas/Widget") + require.NotNil(t, widget) + return usage[widget.Node], true +} + +func TestRequiredOneOfBranchesThatCannotBeChecked(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct { + name, schema string + direction schemaDirection + known bool + }{ + {"branches that accept different types", "{oneOf: [" + widget + ", {type: array}]}", responseSchema, true}, + {"oneOf that is not a list", "{oneOf: {first: " + widget + "}}", sharedSchema, true}, + {"type that is not a name", "{oneOf: [" + widget + ", {type: [string, {a: b}]}]}", sharedSchema, true}, + {"type that is not a name or a list", "{oneOf: [" + widget + ", {type: {a: b}}]}", sharedSchema, true}, + {"empty list of types", "{oneOf: [" + widget + ", {type: []}]}", sharedSchema, true}, + {"reference cycle", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Loop'}]}", sharedSchema, true}, + {"reference to nothing", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing'}]}", 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + direction, known := widgetUsage(t, tc.schema) + assert.Equal(t, tc.known, known) + assert.Equal(t, tc.direction, direction) + }) + } +} diff --git a/what-changed/model/schema_usage_test.go b/what-changed/model/schema_usage_test.go index c20977e1..04476b07 100644 --- a/what-changed/model/schema_usage_test.go +++ b/what-changed/model/schema_usage_test.go @@ -196,7 +196,7 @@ func TestRequiredConservativeSchemaContexts(t *testing.T) { }{ {"negated", "not: " + ref, true}, {"conditional predicate", "if: " + ref, true}, - {"exclusive union", "oneOf: [" + ref + "]", true}, + {"exclusive union of one branch", "oneOf: [" + ref + "]", false}, {"array items", "type: array, items: " + ref, false}, {"allOf reference", "allOf: [" + ref + "]", false}, {"property named not", "properties: {not: " + ref + "}", false}, From 8969ccbe3cf8e5ebebb18e9f9ce30ff4c48ad79e Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 23 Nov 2026 15:14:43 +0100 Subject: [PATCH 02/11] fix(what-changed): follow $ref before type when checking oneOf branches OpenAPI 3.0 ignores the siblings of $ref, so a branch such as {$ref: Other, type: string} accepts what Other accepts. The exclusivity check read the sibling type first, so it could treat overlapping branches as exclusive and relax a change that can break a client. The check now follows the reference first, which is an upper bound in 3.0 and in 3.1. It also only accepts the JSON Schema type names, so an unknown name such as Object no longer counts as a distinct type, and duplicate types inside one branch no longer count as an overlap. Exclusive branches keep the direction in requests as well, so a required entry removed from a request-only union is not breaking either. Tests now cover that, OpenAPI 3.0 documents, and the cases above. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 48 +++++++++++-------- what-changed/model/schema_usage_oneof_test.go | 46 +++++++++++++++++- 2 files changed, 72 insertions(+), 22 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 3da3c874..eff5cea9 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -264,8 +264,10 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc case v3.NotLabel, v3.IfLabel, v3.ContainsLabel: w.walk(value, schemaObject, sharedSchema) case v3.OneOfLabel: - // An exclusive union rejects an instance that matches two branches, so a branch that gains data can make - // a second one match. Branches that cannot match the same instance cannot interfere, as with anyOf. + // A oneOf rejects an instance that matches more than one branch, so changing one branch can change what the + // union accepts in the opposite direction: widening a branch can make an instance match a second one, and + // narrowing it can leave an instance that matched two branches with only one. Branches that no instance can + // match at the same time cannot interfere with each other, so they keep the direction, as with anyOf. if w.exclusiveBranches(value) { w.each(value, schemaObject, sameInstance) } else { @@ -297,7 +299,7 @@ func (w *usageWalker) exclusiveBranches(branches *yaml.Node) bool { if !ok { return false } - for _, t := range types { + for t := range types { if seen[t] { return false } @@ -307,9 +309,16 @@ func (w *usageWalker) exclusiveBranches(branches *yaml.Node) bool { return true } -// instanceTypes lists the JSON types a schema can accept, following local references. Any other keyword can only -// narrow that list, so it is a safe upper bound. It reports false when the schema does not state its type. -func (w *usageWalker) instanceTypes(node *yaml.Node) ([]string, bool) { +// jsonTypes are the instance types of JSON Schema. A type name outside this list cannot be compared with another one. +var jsonTypes = map[string]bool{ + "null": true, "boolean": true, "object": true, "array": true, "number": true, "string": true, "integer": true, +} + +// instanceTypes returns an upper bound of the JSON types a schema accepts. A reference is followed before anything +// else, because OpenAPI 3.0 ignores the siblings of $ref, and in 3.1 they can only narrow the referenced schema. +// It reports false when it cannot tell: a schema without a type, a type name that is not a JSON type, a boolean +// schema, a reference that cannot be resolved, or a chain of references longer than maxReferenceDepth. +func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { const maxReferenceDepth = 8 for range maxReferenceDepth { node = utils.NodeAlias(node) @@ -317,7 +326,7 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) ([]string, bool) { return nil, false } var declared *yaml.Node - var ref string + ref := "" nullable := false for key, value := range usageFields(node) { switch key { @@ -325,42 +334,41 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) ([]string, bool) { declared = utils.NodeAlias(value) case v3.RefLabel: ref = utils.NodeAlias(value).Value - case "nullable": + case v3.NullableLabel: nullable = utils.NodeAlias(value).Value == "true" } } - if declared == nil { - if ref == "" { - return nil, false - } + if ref != "" { if node = w.localTarget(ref); node == nil { return nil, false } continue } + if declared == nil { + return nil, false + } var names []string switch declared.Kind { case yaml.ScalarNode: names = []string{declared.Value} case yaml.SequenceNode: for _, item := range declared.Content { - if utils.NodeAlias(item).Kind != yaml.ScalarNode { - return nil, false - } names = append(names, utils.NodeAlias(item).Value) } - default: - return nil, false } + // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing, so null only widens the bound. if nullable { names = append(names, "null") } - var types []string + types := make(map[string]bool) for _, name := range names { - types = append(types, name) + if !jsonTypes[name] { + return nil, false + } + types[name] = true // Every integer is a number, so the two overlap. if name == "number" { - types = append(types, "integer") + types["integer"] = true } } return types, len(types) > 0 diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index 0fcc2bf2..8988c562 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -33,7 +33,9 @@ func TestRequiredOneOfBranches(t *testing.T) { {"integer and number", "oneOf: [{type: integer}, {type: number}, " + widget + "]", true}, {"branch without a type", "oneOf: [" + widget + ", {properties: {other: {type: string}}}]", true}, {"boolean branch", "oneOf: [" + widget + ", true]", true}, - {"nullable branches", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: true}]", true}, + {"type that is not a JSON type", "oneOf: [" + widget + ", {type: Object}]", true}, + {"integer and number in one branch", "oneOf: [{type: [integer, number]}, " + widget + "]", false}, + {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Page', type: string}]", true}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) @@ -56,6 +58,45 @@ func TestRequiredOneOfBranchesKeepTheirDirection(t *testing.T) { requireEntryBreaking(t, usageSpec(op, usageWidget("name, id")), usageSpec(op, usageWidget("name")), true) } +func TestRequiredOneOfBranchesOpenAPI30(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + const other = "\n Other: {type: object, properties: {other: {type: string}}}" + for _, tc := range []struct { + name, schema string + breaking bool + }{ + // OpenAPI 3.0 ignores the siblings of $ref, so the second branch is an object like Widget. + {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other', type: string}]", true}, + {"nullable object or string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string}]", false}, + {"nullable branches", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: true}]", true}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) + build := func(required string) string { + return strings.Replace(usageSpec(op, usageWidget(required)+other), "openapi: 3.1.0", "openapi: 3.0.3", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), tc.breaking) + }) + } +} + +func TestRequiredOneOfBranchesInARequest(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct { + name, schema string + breaking bool + }{ + // A request may now leave out the property, and no instance can match the other branch as well. + {"branches that accept different types", "oneOf: [" + widget + ", {type: array}]", false}, + {"two objects", "oneOf: [" + widget + ", {type: object, required: [other], properties: {other: {type: string}}}]", true}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageRequestOnly, widget, "{"+tc.schema+"}", 1) + requireEntryBreaking(t, usageSpec(op, usageWidget("name, id")), usageSpec(op, usageWidget("name")), tc.breaking) + }) + } +} + // widgetUsage returns the direction of Widget in a document whose only response schema is the given YAML. The second // result is false when the usage of the document is unknown. func widgetUsage(t *testing.T, schema string) (schemaDirection, bool) { @@ -87,7 +128,7 @@ components: return usage[widget.Node], true } -func TestRequiredOneOfBranchesThatCannotBeChecked(t *testing.T) { +func TestSchemaUsageOneOfBranches(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" for _, tc := range []struct { name, schema string @@ -98,6 +139,7 @@ func TestRequiredOneOfBranchesThatCannotBeChecked(t *testing.T) { {"oneOf that is not a list", "{oneOf: {first: " + widget + "}}", sharedSchema, true}, {"type that is not a name", "{oneOf: [" + widget + ", {type: [string, {a: b}]}]}", sharedSchema, true}, {"type that is not a name or a list", "{oneOf: [" + widget + ", {type: {a: b}}]}", sharedSchema, true}, + {"reference that cannot be resolved next to a type", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing', type: string}]}", 0, false}, {"empty list of types", "{oneOf: [" + widget + ", {type: []}]}", sharedSchema, true}, {"reference cycle", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Loop'}]}", sharedSchema, true}, {"reference to nothing", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing'}]}", 0, false}, From 080afa40230b4397d0ef0abde4f898fa429b93d0 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 09:16:14 +0100 Subject: [PATCH 03/11] perf(what-changed): skip the oneOf branch check when the direction is already shared When the enclosing direction is already shared, the branches get the same direction whether they are exclusive or not, so checking them only costs allocations. Webhooks and callbacks are always shared, and with 128 webhook unions the usage walk went from 72 allocations to 840. The check now only runs when its result can change the direction, which brings it back to 72. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index eff5cea9..5a197b74 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -268,7 +268,8 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc // union accepts in the opposite direction: widening a branch can make an instance match a second one, and // narrowing it can leave an instance that matched two branches with only one. Branches that no instance can // match at the same time cannot interfere with each other, so they keep the direction, as with anyOf. - if w.exclusiveBranches(value) { + // A shared direction is the same either way, so the branches are only checked when it is not. + if sameInstance != sharedSchema && w.exclusiveBranches(value) { w.each(value, schemaObject, sameInstance) } else { w.each(value, schemaObject, sharedSchema) From f231831b6a3c57483f30e22267986ec216d093dc Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 09:17:18 +0100 Subject: [PATCH 04/11] fix(what-changed): read nullable as the schema model does, and only in OpenAPI 3.0 The exclusivity check compared the text of nullable with "true", while the schema model accepts any YAML boolean and parses it with strconv.ParseBool. A branch with nullable: True or TRUE was not seen as accepting null, so two nullable branches could look exclusive and a breaking change was not reported. A quoted 'true' went the other way: the model ignores it, the check did not. OpenAPI 3.1 removed nullable, so it no longer adds null there. When the version cannot be resolved, nullable still adds null, which can only make the result less precise and never hides a breaking change. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 15 +++++++++++---- what-changed/model/schema_usage_oneof_test.go | 7 +++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 5a197b74..b55aa779 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -6,6 +6,7 @@ package model import ( "context" "iter" + "strconv" "strings" "sync" @@ -106,6 +107,8 @@ type usageWalker struct { visited [schemaObject + 1]schemaUsage targets map[string]*yaml.Node unknown bool + // nullable adds null to the types of a schema. Only OpenAPI 3.0 defines it, so it is kept when the version is unknown. + nullable bool } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -116,7 +119,8 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { if root.Kind == yaml.DocumentNode && len(root.Content) > 0 { root = root.Content[0] } - w := usageWalker{index: idx, targets: make(map[string]*yaml.Node)} + version, known := idx.ResolveDocumentVersion() + w := usageWalker{index: idx, targets: make(map[string]*yaml.Node), nullable: !known || version < 3.1} for i := range w.visited { w.visited[i] = make(schemaUsage) } @@ -336,7 +340,10 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { case v3.RefLabel: ref = utils.NodeAlias(value).Value case v3.NullableLabel: - nullable = utils.NodeAlias(value).Value == "true" + // Read it as the schema model does: a YAML boolean, in any spelling that YAML accepts. + if utils.IsNodeBoolValue(value) { + nullable, _ = strconv.ParseBool(utils.NodeAlias(value).Value) + } } } if ref != "" { @@ -357,8 +364,8 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { names = append(names, utils.NodeAlias(item).Value) } } - // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing, so null only widens the bound. - if nullable { + // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing. + if nullable && w.nullable { names = append(names, "null") } types := make(map[string]bool) diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index 8988c562..b1670e8b 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -36,6 +36,8 @@ func TestRequiredOneOfBranches(t *testing.T) { {"type that is not a JSON type", "oneOf: [" + widget + ", {type: Object}]", true}, {"integer and number in one branch", "oneOf: [{type: [integer, number]}, " + widget + "]", false}, {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Page', type: string}]", true}, + // In OpenAPI 3.1 nullable has no effect, so the object branch does not accept null. + {"nullable in OpenAPI 3.1", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: 'null'}]", false}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) @@ -69,6 +71,11 @@ func TestRequiredOneOfBranchesOpenAPI30(t *testing.T) { {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other', type: string}]", true}, {"nullable object or string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string}]", false}, {"nullable branches", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: true}]", true}, + // YAML resolves True and TRUE to the same boolean as true, and the schema model reads them as nullable. + {"nullable branches spelled True", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: True}]", true}, + {"nullable branches spelled TRUE", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: TRUE}]", true}, + // A quoted 'true' is a string, which the schema model does not read as nullable. + {"nullable that is a string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: 'true'}]", false}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) From e9ab33b5126e15ea297404a0a1ca05f9fdb355a4 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 09:17:53 +0100 Subject: [PATCH 05/11] fix(what-changed): only read a single type from a YAML string and ignore nullable on an empty type list The schema model only reads a single type from a YAML string, so an unquoted type: null declares no type and the branch accepts any instance. The exclusivity check read the scalar text as the type name "null", so the branch looked exclusive with an object branch and a breaking change was not reported. An empty list of types already meant that the types cannot be compared, but nullable turned it into "only null". It now stays unknown with or without nullable. Items of a type list are still read by their text, as the schema model reads them: type: [null] is "null" there as well. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 12 ++++++++---- what-changed/model/schema_usage_oneof_test.go | 5 +++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index b55aa779..82bf2ab2 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -356,14 +356,18 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { return nil, false } var names []string - switch declared.Kind { - case yaml.ScalarNode: + switch { + // The schema model only reads a single type from a YAML string, so `type: null` declares no type at all. + case utils.IsNodeStringValue(declared): names = []string{declared.Value} - case yaml.SequenceNode: + case declared.Kind == yaml.SequenceNode: for _, item := range declared.Content { names = append(names, utils.NodeAlias(item).Value) } } + if len(names) == 0 { + return nil, false + } // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing. if nullable && w.nullable { names = append(names, "null") @@ -379,7 +383,7 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { types["integer"] = true } } - return types, len(types) > 0 + return types, true } return nil, false } diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index b1670e8b..0e458c4e 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -36,6 +36,8 @@ func TestRequiredOneOfBranches(t *testing.T) { {"type that is not a JSON type", "oneOf: [" + widget + ", {type: Object}]", true}, {"integer and number in one branch", "oneOf: [{type: [integer, number]}, " + widget + "]", false}, {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Page', type: string}]", true}, + // An unquoted null is not a type name: the schema model leaves the type unset, so the branch accepts anything. + {"type that is a YAML null", "oneOf: [" + widget + ", {type: null}]", true}, // In OpenAPI 3.1 nullable has no effect, so the object branch does not accept null. {"nullable in OpenAPI 3.1", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: 'null'}]", false}, } { @@ -76,6 +78,8 @@ func TestRequiredOneOfBranchesOpenAPI30(t *testing.T) { {"nullable branches spelled TRUE", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: TRUE}]", true}, // A quoted 'true' is a string, which the schema model does not read as nullable. {"nullable that is a string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: 'true'}]", false}, + // An empty list of types cannot be compared, and nullable does not change that. + {"nullable empty list of types", "oneOf: [" + widget + ", {type: [], nullable: true}]", true}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) @@ -149,6 +153,7 @@ func TestSchemaUsageOneOfBranches(t *testing.T) { {"reference that cannot be resolved next to a type", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing', type: string}]}", 0, false}, {"empty list of types", "{oneOf: [" + widget + ", {type: []}]}", sharedSchema, true}, {"reference cycle", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Loop'}]}", sharedSchema, true}, + {"empty list of types that is nullable", "{oneOf: [" + widget + ", {type: [], nullable: true}]}", sharedSchema, true}, {"reference to nothing", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing'}]}", 0, false}, } { t.Run(tc.name, func(t *testing.T) { From 92729f442ae44139d981172ba137599f8e4157b2 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 09:18:37 +0100 Subject: [PATCH 06/11] fix(what-changed): stop at a repeated reference instead of after eight The exclusivity check gave up after following eight references, so a branch behind seven references was compared by type and the same branch behind eight was not, which changed the result. It now records the nodes it follows and stops at one it has seen before, so the length of a chain no longer matters and a cycle still falls back. The record has room for eight nodes and does not escape, so common chains do not allocate. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 11 ++++++----- what-changed/model/schema_usage_oneof_test.go | 17 +++++++++++++++-- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 82bf2ab2..4bbe1596 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -6,6 +6,7 @@ package model import ( "context" "iter" + "slices" "strconv" "strings" "sync" @@ -322,14 +323,15 @@ var jsonTypes = map[string]bool{ // instanceTypes returns an upper bound of the JSON types a schema accepts. A reference is followed before anything // else, because OpenAPI 3.0 ignores the siblings of $ref, and in 3.1 they can only narrow the referenced schema. // It reports false when it cannot tell: a schema without a type, a type name that is not a JSON type, a boolean -// schema, a reference that cannot be resolved, or a chain of references longer than maxReferenceDepth. +// schema, a reference that cannot be resolved, or a cycle of references. func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { - const maxReferenceDepth = 8 - for range maxReferenceDepth { + followed := make([]*yaml.Node, 0, 8) + for { node = utils.NodeAlias(node) - if node.Kind != yaml.MappingNode { + if node.Kind != yaml.MappingNode || slices.Contains(followed, node) { return nil, false } + followed = append(followed, node) var declared *yaml.Node ref := "" nullable := false @@ -385,7 +387,6 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { } return types, true } - return nil, false } // Other dialects may introduce applicators that the OpenAPI schema walk cannot follow. diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index 0e458c4e..87608d3d 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -18,7 +18,15 @@ func TestRequiredOneOfBranches(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" const extra = ` List: {type: array, items: {$ref: '#/components/schemas/Widget'}} - Page: {type: object, properties: {item: {$ref: '#/components/schemas/Widget'}}}` + Page: {type: object, properties: {item: {$ref: '#/components/schemas/Widget'}}} + Alias1: {$ref: '#/components/schemas/Alias2'} + Alias2: {$ref: '#/components/schemas/Alias3'} + Alias3: {$ref: '#/components/schemas/Alias4'} + Alias4: {$ref: '#/components/schemas/Alias5'} + Alias5: {$ref: '#/components/schemas/Alias6'} + Alias6: {$ref: '#/components/schemas/Alias7'} + Alias7: {$ref: '#/components/schemas/Alias8'} + Alias8: {type: string}` for _, tc := range []struct { name, schema string breaking bool @@ -40,6 +48,8 @@ func TestRequiredOneOfBranches(t *testing.T) { {"type that is a YAML null", "oneOf: [" + widget + ", {type: null}]", true}, // In OpenAPI 3.1 nullable has no effect, so the object branch does not accept null. {"nullable in OpenAPI 3.1", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: 'null'}]", false}, + // The length of a chain of references does not change the types its end accepts. + {"chain of eight references", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias1'}]", false}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) @@ -126,7 +136,9 @@ paths: components: schemas: Widget: {type: object} - Loop: {$ref: '#/components/schemas/Loop'}` + Loop: {$ref: '#/components/schemas/Loop'} + LoopA: {$ref: '#/components/schemas/LoopB'} + LoopB: {$ref: '#/components/schemas/LoopA'}` var root yaml.Node require.NoError(t, yaml.Unmarshal([]byte(spec), &root)) idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) @@ -153,6 +165,7 @@ func TestSchemaUsageOneOfBranches(t *testing.T) { {"reference that cannot be resolved next to a type", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing', type: string}]}", 0, false}, {"empty list of types", "{oneOf: [" + widget + ", {type: []}]}", sharedSchema, true}, {"reference cycle", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Loop'}]}", sharedSchema, true}, + {"reference cycle through two schemas", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/LoopA'}]}", sharedSchema, true}, {"empty list of types that is nullable", "{oneOf: [" + widget + ", {type: [], nullable: true}]}", sharedSchema, true}, {"reference to nothing", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing'}]}", 0, false}, } { From 1f3e494230f5783a48fa81dc99dd6ca2b291b8a9 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 09:43:32 +0100 Subject: [PATCH 07/11] fix(what-changed): narrow a oneOf branch by the type next to its $ref in OpenAPI 3.1 In OpenAPI 3.1 the keywords next to $ref apply as well, so a type next to a reference narrows what the branch accepts. The exclusivity check only read the referenced schema, so {$ref: X, type: string} with X accepting strings and objects overlapped with an object branch, while the same branch written inline did not. The types along the reference chain are now intersected, which also gives a type to a reference whose target declares none. This only applies when the version is known to be 3.1 or later and TransformSiblingRefs is on, because that is the only configuration in which the schema model reads the siblings too. Without it, the model reads only the reference, and so does the check. OpenAPI 3.0 ignores the siblings, so nothing changes there. Types along the references that have nothing in common, such as a reference to an object next to type: string, accept no instance at all. That is more likely a mistake than a schema, so the branch stays unknown instead of being treated as exclusive. A type next to a reference that cannot be read makes the branch unknown as well. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 97 ++++++++++++------- what-changed/model/schema_usage_oneof_test.go | 48 ++++++++- 2 files changed, 109 insertions(+), 36 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 4bbe1596..98e50bd2 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -110,6 +110,9 @@ type usageWalker struct { unknown bool // nullable adds null to the types of a schema. Only OpenAPI 3.0 defines it, so it is kept when the version is unknown. nullable bool + // siblings applies the keywords next to $ref as well. OpenAPI 3.1 does, and the schema model only reads them that + // way with TransformSiblingRefs, so without both only the referenced schema counts. + siblings bool } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -121,7 +124,12 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { root = root.Content[0] } version, known := idx.ResolveDocumentVersion() - w := usageWalker{index: idx, targets: make(map[string]*yaml.Node), nullable: !known || version < 3.1} + w := usageWalker{ + index: idx, + targets: make(map[string]*yaml.Node), + nullable: !known || version < 3.1, + siblings: known && version >= 3.1 && idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, + } for i := range w.visited { w.visited[i] = make(schemaUsage) } @@ -320,11 +328,13 @@ var jsonTypes = map[string]bool{ "null": true, "boolean": true, "object": true, "array": true, "number": true, "string": true, "integer": true, } -// instanceTypes returns an upper bound of the JSON types a schema accepts. A reference is followed before anything -// else, because OpenAPI 3.0 ignores the siblings of $ref, and in 3.1 they can only narrow the referenced schema. -// It reports false when it cannot tell: a schema without a type, a type name that is not a JSON type, a boolean -// schema, a reference that cannot be resolved, or a cycle of references. +// instanceTypes returns an upper bound of the JSON types a schema accepts. OpenAPI 3.0 ignores the siblings of $ref, so +// only the referenced schema counts there. In 3.1 they apply as well, so a type next to a reference narrows the bound. +// It reports false when it cannot tell: no type along the references, a type that cannot be read, a boolean schema, a +// reference that cannot be resolved, a cycle of references, or types along the references that have nothing in common, +// which is more likely a mistake than a schema that accepts nothing. func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { + var bound map[string]bool followed := make([]*yaml.Node, 0, 8) for { node = utils.NodeAlias(node) @@ -348,45 +358,66 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { } } } - if ref != "" { - if node = w.localTarget(ref); node == nil { + if declared != nil && (ref == "" || w.siblings) { + types, ok := w.declaredTypes(declared, nullable) + if !ok { return nil, false } - continue + bound = intersectTypes(bound, types) + } + if ref == "" { + return bound, len(bound) > 0 } - if declared == nil { + if node = w.localTarget(ref); node == nil { return nil, false } - var names []string - switch { - // The schema model only reads a single type from a YAML string, so `type: null` declares no type at all. - case utils.IsNodeStringValue(declared): - names = []string{declared.Value} - case declared.Kind == yaml.SequenceNode: - for _, item := range declared.Content { - names = append(names, utils.NodeAlias(item).Value) - } + } +} + +// declaredTypes returns the JSON types of a type declaration, or false when it cannot be read. +func (w *usageWalker) declaredTypes(declared *yaml.Node, nullable bool) (map[string]bool, bool) { + var names []string + switch { + // The schema model only reads a single type from a YAML string, so `type: null` declares no type at all. + case utils.IsNodeStringValue(declared): + names = []string{declared.Value} + case declared.Kind == yaml.SequenceNode: + for _, item := range declared.Content { + names = append(names, utils.NodeAlias(item).Value) } - if len(names) == 0 { + } + if len(names) == 0 { + return nil, false + } + // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing. + if nullable && w.nullable { + names = append(names, "null") + } + types := make(map[string]bool) + for _, name := range names { + if !jsonTypes[name] { return nil, false } - // OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing. - if nullable && w.nullable { - names = append(names, "null") + types[name] = true + // Every integer is a number, so the two overlap. + if name == "number" { + types["integer"] = true } - types := make(map[string]bool) - for _, name := range names { - if !jsonTypes[name] { - return nil, false - } - types[name] = true - // Every integer is a number, so the two overlap. - if name == "number" { - types["integer"] = true - } + } + return types, true +} + +// intersectTypes narrows bound to the types it shares with types. A nil bound does not restrict anything yet. +func intersectTypes(bound, types map[string]bool) map[string]bool { + if bound == nil { + return types + } + for t := range bound { + if !types[t] { + delete(bound, t) } - return types, true } + return bound } // Other dialects may introduce applicators that the OpenAPI schema walk cannot follow. diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index 87608d3d..3541a6d9 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -9,6 +9,8 @@ import ( "testing" "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/datamodel" + v3 "github.com/pb33f/libopenapi/datamodel/low/v3" "github.com/pb33f/libopenapi/index" "github.com/pb33f/testify/assert" "github.com/pb33f/testify/require" @@ -26,7 +28,10 @@ func TestRequiredOneOfBranches(t *testing.T) { Alias5: {$ref: '#/components/schemas/Alias6'} Alias6: {$ref: '#/components/schemas/Alias7'} Alias7: {$ref: '#/components/schemas/Alias8'} - Alias8: {type: string}` + Alias8: {type: string} + StringOrObject: {type: [string, object]} + Narrowed: {$ref: '#/components/schemas/StringOrObject', type: string} + Untyped: {minLength: 1}` for _, tc := range []struct { name, schema string breaking bool @@ -43,7 +48,15 @@ func TestRequiredOneOfBranches(t *testing.T) { {"boolean branch", "oneOf: [" + widget + ", true]", true}, {"type that is not a JSON type", "oneOf: [" + widget + ", {type: Object}]", true}, {"integer and number in one branch", "oneOf: [{type: [integer, number]}, " + widget + "]", false}, + // The type next to the reference and the type behind it have nothing in common, which is more likely a mistake + // than a schema that accepts nothing. {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Page', type: string}]", true}, + // In OpenAPI 3.1 the siblings of $ref apply as well, so a type next to a reference narrows it. + {"reference next to a narrower type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: string}]", false}, + {"reference narrowed to the type of another branch", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: object}]", true}, + {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", false}, + {"type next to a reference along the chain", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Narrowed'}]", false}, + {"reference next to a type that is not a JSON type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias8', type: Object}]", true}, // An unquoted null is not a type name: the schema model leaves the type unset, so the branch accepts anything. {"type that is a YAML null", "oneOf: [" + widget + ", {type: null}]", true}, // In OpenAPI 3.1 nullable has no effect, so the object branch does not accept null. @@ -74,13 +87,14 @@ func TestRequiredOneOfBranchesKeepTheirDirection(t *testing.T) { func TestRequiredOneOfBranchesOpenAPI30(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" - const other = "\n Other: {type: object, properties: {other: {type: string}}}" + const other = "\n Other: {type: object, properties: {other: {type: string}}}\n Untyped: {minLength: 1}" for _, tc := range []struct { name, schema string breaking bool }{ // OpenAPI 3.0 ignores the siblings of $ref, so the second branch is an object like Widget. {"reference next to a type", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other', type: string}]", true}, + {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", true}, {"nullable object or string", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string}]", false}, {"nullable branches", "oneOf: [{type: object, nullable: true, properties: {item: " + widget + "}}, {type: string, nullable: true}]", true}, // YAML resolves True and TRUE to the same boolean as true, and the schema model reads them as nullable. @@ -101,6 +115,31 @@ func TestRequiredOneOfBranchesOpenAPI30(t *testing.T) { } } +// Without TransformSiblingRefs the schema model reads only the reference, so a type next to it narrows nothing. +func TestRequiredOneOfBranchesWithoutSiblingTransform(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + union := "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: string}]" + op := strings.Replace(usageResponseOnly, widget, "{"+union+"}", 1) + build := func(required string) *v3.Document { + info, err := datamodel.ExtractSpecInfo([]byte(usageSpec(op, usageWidget(required)+"\n StringOrObject: {type: [string, object]}"))) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = false + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.True(t, ch.Breaking) + return + } + } + t.Fatal("missing required change") +} + func TestRequiredOneOfBranchesInARequest(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" for _, tc := range []struct { @@ -138,7 +177,8 @@ components: Widget: {type: object} Loop: {$ref: '#/components/schemas/Loop'} LoopA: {$ref: '#/components/schemas/LoopB'} - LoopB: {$ref: '#/components/schemas/LoopA'}` + LoopB: {$ref: '#/components/schemas/LoopA'} + Untyped: {minLength: 1}` var root yaml.Node require.NoError(t, yaml.Unmarshal([]byte(spec), &root)) idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) @@ -167,6 +207,8 @@ func TestSchemaUsageOneOfBranches(t *testing.T) { {"reference cycle", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Loop'}]}", sharedSchema, true}, {"reference cycle through two schemas", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/LoopA'}]}", sharedSchema, true}, {"empty list of types that is nullable", "{oneOf: [" + widget + ", {type: [], nullable: true}]}", sharedSchema, true}, + // Without a known version, the siblings of $ref may be ignored, so only the reference counts. + {"reference without a type next to a type in an unknown version", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Untyped', type: string}]}", sharedSchema, true}, {"reference to nothing", "{oneOf: [" + widget + ", {$ref: '#/components/schemas/Missing'}]}", 0, false}, } { t.Run(tc.name, func(t *testing.T) { From 8482b7ff32cbcdf2fedacd584dc38cd660f015c2 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 14:54:53 +0100 Subject: [PATCH 08/11] fix(datamodel): read the value an alias points to in a list of types An alias node keeps the name of its anchor as its value, and the schema model read each item of a type list from that value. With x-type: &object string, type: [*object] was read as object instead of string, so the schema hashed differently from type: [string] and rendered as type: [object]. The exclusivity check of a oneOf already followed the alias, so a branch read as string there while the model stored object. Requiring a property of an object branch next to it was not breaking, but became breaking once both documents were rendered and read back. The model now follows the alias as well, as it already does for a single type and for an alias to a whole list. Co-Authored-By: Claude --- datamodel/low/base/schema_build.go | 6 +++-- datamodel/low/base/schema_test.go | 20 ++++++++++++++ what-changed/model/schema_usage_oneof_test.go | 27 ++++++++++++++++++- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/datamodel/low/base/schema_build.go b/datamodel/low/base/schema_build.go index b2016773..dab25056 100644 --- a/datamodel/low/base/schema_build.go +++ b/datamodel/low/base/schema_build.go @@ -138,9 +138,11 @@ func (s *Schema) Build(ctx context.Context, root *yaml.Node, idx *index.SpecInde if utils.IsNodeArray(typeValue) { refs := make([]low.ValueReference[string], 0, len(typeValue.Content)) for r := range typeValue.Content { + // An alias keeps the anchor name as its value, so read the node it points to. + item := utils.NodeAlias(typeValue.Content[r]) refs = append(refs, low.ValueReference[string]{ - Value: typeValue.Content[r].Value, - ValueNode: typeValue.Content[r], + Value: item.Value, + ValueNode: item, }) } s.Type = low.NodeReference[SchemaDynamicValue[string, []low.ValueReference[string]]]{ diff --git a/datamodel/low/base/schema_test.go b/datamodel/low/base/schema_test.go index 2614a407..7eaa6911 100644 --- a/datamodel/low/base/schema_test.go +++ b/datamodel/low/base/schema_test.go @@ -506,6 +506,26 @@ const: tasty` assert.Equal(t, "tasty", schConst) } +func TestSchema_Build_TypeListWithAlias(t *testing.T) { + build := func(spec string) *Schema { + var rootNode yaml.Node + assert.NoError(t, yaml.Unmarshal([]byte(spec), &rootNode)) + sch := Schema{} + assert.NoError(t, low.BuildModel(rootNode.Content[0].Content[3], &sch)) + assert.NoError(t, sch.Build(context.Background(), rootNode.Content[0].Content[3], nil)) + return &sch + } + // An alias in a list of types reads the value it points to, not the name of its anchor. + aliased := build("name: &object string\nschema: {type: [*object, 'null']}") + plain := build("name: string\nschema: {type: [string, 'null']}") + assert.True(t, aliased.Type.Value.IsB()) + if assert.Len(t, aliased.Type.Value.B, 2) { + assert.Equal(t, "string", aliased.Type.Value.B[0].Value) + assert.Equal(t, "null", aliased.Type.Value.B[1].Value) + } + assert.Equal(t, plain.Hash(), aliased.Hash()) +} + func TestSchema_Build_PropsLookup(t *testing.T) { yml := `components: schemas: diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index 3541a6d9..d6f75639 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -10,6 +10,7 @@ import ( "github.com/pb33f/go-yaml" "github.com/pb33f/libopenapi/datamodel" + highv3 "github.com/pb33f/libopenapi/datamodel/high/v3" v3 "github.com/pb33f/libopenapi/datamodel/low/v3" "github.com/pb33f/libopenapi/index" "github.com/pb33f/testify/assert" @@ -31,7 +32,9 @@ func TestRequiredOneOfBranches(t *testing.T) { Alias8: {type: string} StringOrObject: {type: [string, object]} Narrowed: {$ref: '#/components/schemas/StringOrObject', type: string} - Untyped: {minLength: 1}` + Untyped: {minLength: 1} + Named: {type: &object string} + AliasedType: {type: [*object]}` for _, tc := range []struct { name, schema string breaking bool @@ -57,6 +60,8 @@ func TestRequiredOneOfBranches(t *testing.T) { {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", false}, {"type next to a reference along the chain", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Narrowed'}]", false}, {"reference next to a type that is not a JSON type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias8', type: Object}]", true}, + // An alias in a list of types reads the value it points to, not the name of its anchor. + {"alias in a list of types", "oneOf: [" + widget + ", {$ref: '#/components/schemas/AliasedType'}]", false}, // An unquoted null is not a type name: the schema model leaves the type unset, so the branch accepts anything. {"type that is a YAML null", "oneOf: [" + widget + ", {type: null}]", true}, // In OpenAPI 3.1 nullable has no effect, so the object branch does not accept null. @@ -74,6 +79,26 @@ func TestRequiredOneOfBranches(t *testing.T) { } } +// Rendering a document and reading it back must not change whether the branches are exclusive. +func TestRequiredOneOfBranchesAfterRendering(t *testing.T) { + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct{ name, schema, extra string }{ + {"alias in a list of types", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other'}]", "\n x-type: &object string\n Other: {type: [*object]}"}, + } { + t.Run(tc.name, func(t *testing.T) { + op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) + left, right := usageSpec(op, usageWidget("name")+tc.extra), usageSpec(op, usageWidget("name, id")+tc.extra) + requireEntryBreaking(t, left, right, false) + render := func(spec string) string { + rendered, err := highv3.NewDocument(buildUsageDocument(t, spec)).Render() + require.NoError(t, err) + return string(rendered) + } + requireEntryBreaking(t, render(left), render(right), false) + }) + } +} + func TestRequiredOneOfBranchesKeepTheirDirection(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" union := "oneOf: [{type: array, items: " + widget + "}, {type: object, properties: {widgets: {type: array, items: " + widget + "}}}]" From 10165a4061caa15f0ac4d150e208b8b2faf11e5d Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 14:55:06 +0100 Subject: [PATCH 09/11] fix(what-changed): let a reference to the boolean schema true keep the type next to it The boolean schema true accepts every instance, as {} does. In OpenAPI 3.1 a reference to {} next to type: string was read as a string branch, but a reference to true made the branch unknown, because the check gave up on any target that is not a mapping. Requiring a property of an object branch next to it was therefore breaking with true and not with {}. A reference to true now narrows nothing, like {}. The boolean schema false accepts nothing, which is more likely a mistake than a branch that no instance matches, so it still makes the branch unknown, as types that have nothing in common do. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 12 +++++++++--- what-changed/model/schema_usage_oneof_test.go | 9 +++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 98e50bd2..49174b8c 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -330,14 +330,20 @@ var jsonTypes = map[string]bool{ // instanceTypes returns an upper bound of the JSON types a schema accepts. OpenAPI 3.0 ignores the siblings of $ref, so // only the referenced schema counts there. In 3.1 they apply as well, so a type next to a reference narrows the bound. -// It reports false when it cannot tell: no type along the references, a type that cannot be read, a boolean schema, a -// reference that cannot be resolved, a cycle of references, or types along the references that have nothing in common, -// which is more likely a mistake than a schema that accepts nothing. +// It reports false when it cannot tell: no type along the references, a type that cannot be read, a reference that +// cannot be resolved, a cycle of references, or types along the references that have nothing in common, which is more +// likely a mistake than a schema that accepts nothing. The same goes for the boolean schema false. func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { var bound map[string]bool followed := make([]*yaml.Node, 0, 8) for { node = utils.NodeAlias(node) + // The boolean schema true accepts every instance, like {}, so it narrows nothing. + if utils.IsNodeBoolValue(node) { + if accepts, _ := strconv.ParseBool(node.Value); accepts { + return bound, len(bound) > 0 + } + } if node.Kind != yaml.MappingNode || slices.Contains(followed, node) { return nil, false } diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index d6f75639..ee79a6ed 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -33,6 +33,9 @@ func TestRequiredOneOfBranches(t *testing.T) { StringOrObject: {type: [string, object]} Narrowed: {$ref: '#/components/schemas/StringOrObject', type: string} Untyped: {minLength: 1} + Anything: {} + Everything: true + Nothing: false Named: {type: &object string} AliasedType: {type: [*object]}` for _, tc := range []struct { @@ -60,6 +63,11 @@ func TestRequiredOneOfBranches(t *testing.T) { {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", false}, {"type next to a reference along the chain", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Narrowed'}]", false}, {"reference next to a type that is not a JSON type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias8', type: Object}]", true}, + // The boolean schema true accepts every instance like {}, so the type next to either reference is what counts. + {"reference to an empty schema next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Anything', type: string}]", false}, + {"reference to true next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Everything', type: string}]", false}, + // The boolean schema false accepts nothing, which is more likely a mistake than a branch that no instance matches. + {"reference to false next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Nothing', type: string}]", true}, // An alias in a list of types reads the value it points to, not the name of its anchor. {"alias in a list of types", "oneOf: [" + widget + ", {$ref: '#/components/schemas/AliasedType'}]", false}, // An unquoted null is not a type name: the schema model leaves the type unset, so the branch accepts anything. @@ -84,6 +92,7 @@ func TestRequiredOneOfBranchesAfterRendering(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" for _, tc := range []struct{ name, schema, extra string }{ {"alias in a list of types", "oneOf: [" + widget + ", {$ref: '#/components/schemas/Other'}]", "\n x-type: &object string\n Other: {type: [*object]}"}, + {"reference to true next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Other', type: string}]", "\n Other: true"}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, widget, "{"+tc.schema+"}", 1) From c3e2e9cbd550a89490db72969591de8ed7813c3d Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 17:28:53 +0100 Subject: [PATCH 10/11] fix(what-changed): only narrow a oneOf branch by a type the model reads next to its $ref In OpenAPI 3.1 with TransformSiblingRefs, the check read the type next to every $ref along the chain of references of a branch, and next to the $ref of a branch that is an alias. The schema model reads neither. When it reaches a schema through a $ref, it follows the $ref of that schema and drops the type next to it. The sibling transform skips an alias in a list, so an aliased branch is read the same way. It does not resolve a $ref whose value is an alias at all. With Narrowed: {$ref: StringOrObject, type: string}, the model reads a branch {$ref: Narrowed}, or an alias of Narrowed, as [string, object], which overlaps an object branch. The check read it as string, so requiring a property of the object branch was not breaking. It is breaking on main, where every oneOf branch is shared. The type next to a $ref now only narrows the branch itself, written in place. A branch whose $ref value is an alias cannot be told apart from the others. A type along the chain that has nothing in common with the referenced schema no longer makes the branch unknown either, because the model does not read it. The test for a type next to a reference along the chain now expects a breaking change. New tests cover a type along the chain that has nothing in common with the referenced schema, a branch that is an alias, and a branch whose $ref value is an alias. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 9 +++- what-changed/model/schema_usage_oneof_test.go | 48 ++++++++++++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 49174b8c..b121dc01 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -330,12 +330,15 @@ var jsonTypes = map[string]bool{ // instanceTypes returns an upper bound of the JSON types a schema accepts. OpenAPI 3.0 ignores the siblings of $ref, so // only the referenced schema counts there. In 3.1 they apply as well, so a type next to a reference narrows the bound. +// That only holds for the schema itself, written in place: the schema model reads a schema it reaches through a $ref +// as the target of its own $ref, without the type next to it, and does the same with an alias in a list. // It reports false when it cannot tell: no type along the references, a type that cannot be read, a reference that // cannot be resolved, a cycle of references, or types along the references that have nothing in common, which is more // likely a mistake than a schema that accepts nothing. The same goes for the boolean schema false. func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { var bound map[string]bool followed := make([]*yaml.Node, 0, 8) + aliased := node != nil && node.Kind == yaml.AliasNode for { node = utils.NodeAlias(node) // The boolean schema true accepts every instance, like {}, so it narrows nothing. @@ -356,6 +359,10 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { case v3.TypeLabel: declared = utils.NodeAlias(value) case v3.RefLabel: + // The model does not resolve a $ref whose value is an alias. + if value.Kind == yaml.AliasNode { + return nil, false + } ref = utils.NodeAlias(value).Value case v3.NullableLabel: // Read it as the schema model does: a YAML boolean, in any spelling that YAML accepts. @@ -364,7 +371,7 @@ func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) { } } } - if declared != nil && (ref == "" || w.siblings) { + if declared != nil && (ref == "" || (w.siblings && len(followed) == 1 && !aliased)) { types, ok := w.declaredTypes(declared, nullable) if !ok { return nil, false diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index ee79a6ed..e13a689b 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -32,6 +32,7 @@ func TestRequiredOneOfBranches(t *testing.T) { Alias8: {type: string} StringOrObject: {type: [string, object]} Narrowed: {$ref: '#/components/schemas/StringOrObject', type: string} + Mismatched: {$ref: '#/components/schemas/Alias8', type: object} Untyped: {minLength: 1} Anything: {} Everything: true @@ -61,7 +62,10 @@ func TestRequiredOneOfBranches(t *testing.T) { {"reference next to a narrower type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: string}]", false}, {"reference narrowed to the type of another branch", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/StringOrObject', type: object}]", true}, {"reference without a type next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Untyped', type: string}]", false}, - {"type next to a reference along the chain", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Narrowed'}]", false}, + // The schema model reads a schema it reaches through a $ref as the target of its own $ref, without the type next + // to it, so only the type next to the $ref of the branch itself counts. + {"type next to a reference along the chain", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Narrowed'}]", true}, + {"type next to a reference along the chain that has nothing in common with it", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Mismatched'}]", false}, {"reference next to a type that is not a JSON type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Alias8', type: Object}]", true}, // The boolean schema true accepts every instance like {}, so the type next to either reference is what counts. {"reference to an empty schema next to a type", "oneOf: [{type: object, properties: {item: " + widget + "}}, {$ref: '#/components/schemas/Anything', type: string}]", false}, @@ -87,6 +91,18 @@ func TestRequiredOneOfBranches(t *testing.T) { } } +func TestRequiredOneOfBranchThatIsAnAlias(t *testing.T) { + // The schema model does not apply TransformSiblingRefs to an alias in a list, so it reads an aliased branch as the + // target of its $ref, without the type next to it. The branch then accepts objects, like the other one. + const widget = "{$ref: '#/components/schemas/Widget'}" + op := strings.Replace(usageResponseOnly, widget, "{oneOf: [{type: object, properties: {item: "+widget+"}}, *narrowed]}", 1) + build := func(required string) string { + spec := usageSpec(op, usageWidget(required)+"\n StringOrObject: {type: [string, object]}") + return strings.Replace(spec, "\npaths:", "\nx-narrowed: &narrowed {$ref: '#/components/schemas/StringOrObject', type: string}\npaths:", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), true) +} + // Rendering a document and reading it back must not change whether the branches are exclusive. func TestRequiredOneOfBranchesAfterRendering(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" @@ -193,6 +209,36 @@ func TestRequiredOneOfBranchesInARequest(t *testing.T) { // widgetUsage returns the direction of Widget in a document whose only response schema is the given YAML. The second // result is false when the usage of the document is unknown. +func TestSchemaUsageOneOfBranchesWithAReferenceThatIsAnAlias(t *testing.T) { + // The model does not resolve a $ref whose value is an alias, so it cannot tell what such a branch accepts. + const widget = "{$ref: '#/components/schemas/Widget'}" + for _, tc := range []struct { + name, schema string + direction schemaDirection + }{ + {"branch that is such a reference", "{oneOf: [" + widget + ", {$ref: *text}]}", sharedSchema}, + {"no such reference", "{oneOf: [" + widget + ", {type: string}]}", responseSchema}, + } { + t.Run(tc.name, func(t *testing.T) { + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`openapi: 3.1.0 +x-refs: {text: &text '#/components/schemas/Text'} +paths: + /widgets: {get: {responses: {'200': {description: ok, content: {application/json: {schema: `+tc.schema+`}}}}}} +components: + schemas: + Widget: {type: object} + Text: {type: string}`), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + usage := buildSchemaUsage(idx) + require.NotNil(t, usage) + widget := idx.FindComponentInRoot(context.Background(), "#/components/schemas/Widget") + require.NotNil(t, widget) + assert.Equal(t, tc.direction, usage[widget.Node]) + }) + } +} + func widgetUsage(t *testing.T, schema string) (schemaDirection, bool) { t.Helper() spec := `openapi: 3.1.0 From 5ad6dfb731c3a50bce348d6273119a2a02757979 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 17:29:32 +0100 Subject: [PATCH 11/11] fix(what-changed): share every oneOf when the walk follows what the model does not read The walk follows the keywords next to a $ref, as it does on main. The schema model drops them without TransformSiblingRefs, when it reaches a schema through a $ref, for an alias in a list, and always next to the $ref of a response, request body, parameter, header or path item. It also does not resolve a $ref whose value is an alias, which the walk follows. The walk can therefore give a schema a direction that the model does not have. On main that did not matter inside a oneOf, because every branch was shared. With this PR, an exclusive union could make it matter, for example: - a oneOf next to the $ref of Holder: {$ref: Other, oneOf: [...]} reached through a $ref, or in the keywords next to it, - an exclusive branch that leads to such keywords, - a union in the content next to the $ref of a response, - Holder reached in the response direction outside a union before the walk reaches it in an exclusive branch, so that the branch skips it. Requiring a property of a schema that only those keywords reach was then not breaking, while it is breaking on main. The walk now records whether it reached a schema through what the model does not read, and whether it kept the direction of a oneOf. When both happen, the document is walked again with every oneOf shared, which gives the same usage as on main, whatever the order. Documents without such keywords keep the direction of their exclusive unions. In OpenAPI 3.0 the model still reads the keywords next to a $ref where the schema is written, so treating them as dropped there only shares more unions. Tests cover a oneOf written next to a $ref, next to a $ref reached through a $ref, in the keywords next to it, in an alias, and such keywords in an exclusive branch, with the transform on and off. Others cover a reference to Holder before and after the union, a union next to the $ref of a response and of a path item, and a $ref whose value is an alias elsewhere, each with a document without such keywords that keeps the direction. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 93 +++++++--- what-changed/model/schema_usage_oneof_test.go | 169 +++++++++++++++++- 2 files changed, 234 insertions(+), 28 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index b121dc01..10c08b55 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -113,6 +113,13 @@ type usageWalker struct { // siblings applies the keywords next to $ref as well. OpenAPI 3.1 does, and the schema model only reads them that // way with TransformSiblingRefs, so without both only the referenced schema counts. siblings bool + // dropped counts the keywords being walked that the model drops next to a $ref. + dropped int + // throughDropped is set once the walk reaches a schema through keywords the model drops next to a $ref, or through + // a $ref the model does not resolve, and madeExclusive once it keeps the direction of the branches of a oneOf. + throughDropped, madeExclusive bool + // sharedUnions shares the branches of every oneOf, as before. + sharedUnions bool } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -124,26 +131,37 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { root = root.Content[0] } version, known := idx.ResolveDocumentVersion() - w := usageWalker{ - index: idx, - targets: make(map[string]*yaml.Node), - nullable: !known || version < 3.1, - siblings: known && version >= 3.1 && idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, - } - for i := range w.visited { - w.visited[i] = make(schemaUsage) - } - for key, value := range usageFields(root) { - switch key { - case v3.JSONSchemaDialectLabel: - if !knownUsageDialect(value) { - return nil + walk := func(sharedUnions bool) *usageWalker { + w := &usageWalker{ + index: idx, + targets: make(map[string]*yaml.Node), + nullable: !known || version < 3.1, + siblings: known && version >= 3.1 && idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, + sharedUnions: sharedUnions, + } + for i := range w.visited { + w.visited[i] = make(schemaUsage) + } + for key, value := range usageFields(root) { + switch key { + case v3.JSONSchemaDialectLabel: + if !knownUsageDialect(value) { + w.unknown = true + return w + } + case v3.PathsLabel: + w.openAPIEntries(value, pathItemObject, 0) + case v3.WebhooksLabel: + w.each(value, pathItemObject, sharedSchema) } - case v3.PathsLabel: - w.openAPIEntries(value, pathItemObject, 0) - case v3.WebhooksLabel: - w.each(value, pathItemObject, sharedSchema) } + return w + } + w := walk(false) + // The walk follows the keywords the model drops next to a $ref, as it did before. That did not matter while every + // oneOf was shared, so the document is walked again that way when both happen. + if !w.unknown && w.madeExclusive && w.throughDropped { + w = walk(true) } if w.unknown { return nil @@ -189,10 +207,19 @@ func (w *usageWalker) each(node *yaml.Node, object usageObject, dir schemaDirect } func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirection) { + w.walkReached(node, object, dir, false) +} + +// walkReached walks node, which referenced tells is reached through a reference rather than written in place. +func (w *usageWalker) walkReached(node *yaml.Node, object usageObject, dir schemaDirection, referenced bool) { + aliased := node != nil && node.Kind == yaml.AliasNode node = utils.NodeAlias(node) if w.unknown || node == nil || node.Kind != yaml.MappingNode { return } + if object == schemaObject && w.dropped > 0 { + w.throughDropped = true + } visited := w.visited[object] if prior, seen := visited[node]; seen && prior&dir == dir { return @@ -213,16 +240,28 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect } } } + // The schema model drops the keywords next to a $ref without TransformSiblingRefs, when it reaches the schema through + // a $ref, and for an alias in a list. Next to the $ref of anything other than a schema, such as a response or a path + // item, it always drops them. The walk still follows them, as before, and records that it did. In OpenAPI 3.0 the + // model still reads them where the schema is written, so treating them as dropped there only shares more unions. + dropped := (object != schemaObject || !w.siblings || referenced || aliased) && usageField(node, v3.RefLabel) != nil for key, value := range usageFields(node) { if key == v3.RefLabel { ref := utils.NodeAlias(value).Value + // The model does not resolve a $ref whose value is an alias, so the walk reaches what the model does not. + if value.Kind == yaml.AliasNode { + w.throughDropped = true + } if target := w.localTarget(ref); target != nil { - w.walk(target, object, sameInstance) + w.walkReached(target, object, sameInstance, true) continue } w.unknown = true return } + if dropped { + w.dropped++ + } switch object { case pathItemObject, operationObject: w.operationField(key, value, dir) @@ -242,6 +281,9 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect case schemaObject: w.schemaField(key, value, dir, sameInstance) } + if dropped { + w.dropped-- + } } } @@ -282,7 +324,8 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc // narrowing it can leave an instance that matched two branches with only one. Branches that no instance can // match at the same time cannot interfere with each other, so they keep the direction, as with anyOf. // A shared direction is the same either way, so the branches are only checked when it is not. - if sameInstance != sharedSchema && w.exclusiveBranches(value) { + if !w.sharedUnions && sameInstance != sharedSchema && w.exclusiveBranches(value) { + w.madeExclusive = true w.each(value, schemaObject, sameInstance) } else { w.each(value, schemaObject, sharedSchema) @@ -433,6 +476,16 @@ func intersectTypes(bound, types map[string]bool) map[string]bool { return bound } +// usageField returns the value of one field of a mapping, or nil when the mapping does not have it. +func usageField(node *yaml.Node, name string) *yaml.Node { + for key, value := range usageFields(node) { + if key == name { + return value + } + } + return nil +} + // Other dialects may introduce applicators that the OpenAPI schema walk cannot follow. func knownUsageDialect(value *yaml.Node) bool { switch strings.TrimSuffix(utils.NodeAlias(value).Value, "#") { diff --git a/what-changed/model/schema_usage_oneof_test.go b/what-changed/model/schema_usage_oneof_test.go index e13a689b..cff5b470 100644 --- a/what-changed/model/schema_usage_oneof_test.go +++ b/what-changed/model/schema_usage_oneof_test.go @@ -5,6 +5,7 @@ package model import ( "context" + "fmt" "strings" "testing" @@ -190,6 +191,154 @@ func TestRequiredOneOfBranchesWithoutSiblingTransform(t *testing.T) { t.Fatal("missing required change") } +func TestRequiredOneOfBranchesInKeywordsTheModelDrops(t *testing.T) { + // The union only reaches Widget through the keywords next to a $ref. The schema model reads them only with + // TransformSiblingRefs, and only where the schema is written: when it reaches a schema through a $ref, or an alias + // in a list, it follows the $ref of that schema and drops the rest. There the branches stay shared, as before. + const widget = "{$ref: '#/components/schemas/Widget'}" + const union = "oneOf: [{type: object, properties: {item: " + widget + "}}, {type: string}]" + const other = "\n Other: {type: object}" + holder := strings.Replace(usageResponseOnly, "Widget", "Holder", 1) + for _, tc := range []struct { + name, operation, schemas string + // breaking is the result with the transform on and then off. + breaking [2]bool + }{ + {"oneOf written next to a reference", + strings.Replace(usageResponseOnly, widget, "{$ref: '#/components/schemas/Other', "+union+"}", 1), + other, [2]bool{false, true}}, + {"oneOf next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', " + union + "}", [2]bool{true, true}}, + {"oneOf in the properties next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', properties: {p: {" + union + "}}}", [2]bool{true, true}}, + {"oneOf next to a reference in an alias", + " x-holder: &holder {$ref: '#/components/schemas/Other', " + union + "}\n" + + strings.Replace(usageResponseOnly, widget, "{anyOf: [*holder]}", 1), + other, [2]bool{true, true}}, + // The keywords the model drops inside an exclusive branch are shared as well. + {"keywords next to a reference in an exclusive branch, reached through a reference", + strings.Replace(usageResponseOnly, widget, "{oneOf: [{type: object, properties: {item: {$ref: '#/components/schemas/Holder'}}}, {type: string}]}", 1), + other + "\n Holder: {$ref: '#/components/schemas/Other', properties: {w: " + widget + "}}", [2]bool{true, true}}, + {"keywords next to a reference written in an exclusive branch", + strings.Replace(usageResponseOnly, widget, "{oneOf: [{$ref: '#/components/schemas/Other', type: object, properties: {item: "+widget+"}}, {type: string}]}", 1), + other, [2]bool{false, true}}, + } { + for i, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { + build := func(required string) *v3.Document { + info, err := datamodel.ExtractSpecInfo([]byte(usageSpec(tc.operation, usageWidget(required)+tc.schemas))) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = transform + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.Equal(t, tc.breaking[i], ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } + } +} + +func TestRequiredOneOfBranchesElsewhereWithKeywordsTheModelDrops(t *testing.T) { + // Widget is only reached through the properties next to the $ref of Holder, which the model drops. One response + // refers to Holder directly and another through an exclusive union, in either order. Before this PR every oneOf was + // shared, so following keywords the model drops did not matter there. When both happen, every oneOf is shared again. + const union = "{oneOf: [{type: object, properties: {item: {$ref: '#/components/schemas/Holder'}}}, {type: string}]}" + const others = ` + /others: + get: + responses: + '200': + description: ok + content: + application/json: + schema: %s` + holder := strings.Replace(usageResponseOnly, "Widget", "Holder", 1) + const dropped = "\n Other: {type: object}\n Holder: {$ref: '#/components/schemas/Other', properties: {w: {$ref: '#/components/schemas/Widget'}}}" + for _, tc := range []struct { + name, first, second, schemas string + breaking bool + }{ + {"reference before the union", holder, fmt.Sprintf(others, union), dropped, true}, + {"union before the reference", strings.Replace(holder, "{$ref: '#/components/schemas/Holder'}", union, 1), fmt.Sprintf(others, "{$ref: '#/components/schemas/Holder'}"), dropped, true}, + {"no keywords next to a reference", holder, fmt.Sprintf(others, union), "\n Holder: {type: object, properties: {w: {$ref: '#/components/schemas/Widget'}}}", false}, + } { + for _, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { + build := func(required string) *v3.Document { + spec := usageSpec(tc.first, usageWidget(required)+tc.schemas) + spec = strings.Replace(spec, "\ncomponents:", tc.second+"\ncomponents:", 1) + info, err := datamodel.ExtractSpecInfo([]byte(spec)) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = transform + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.Equal(t, tc.breaking, ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } + } +} + +func TestRequiredOneOfBranchesNextToTheReferenceOfAResponseOrPathItem(t *testing.T) { + // The model reads a response or path item with a $ref as the one it refers to, and drops the rest. The union next + // to that $ref is the only one that reaches Widget, so its branches stay shared, as before. + const union = "{oneOf: [{type: object, properties: {item: {$ref: '#/components/schemas/Widget'}}}, {type: string}]}" + const content = "content: {application/json: {schema: " + union + "}}" + for _, tc := range []struct { + name, path string + breaking bool + }{ + {"response", " get:\n responses:\n '200': {$ref: '#/components/responses/Empty', " + content + "}", true}, + {"path item", " $ref: '#/components/pathItems/Empty'\n get:\n responses:\n '200': {description: ok, " + content + "}", true}, + {"no reference", " get:\n responses:\n '200': {description: ok, " + content + "}", false}, + } { + for _, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { + build := func(required string) *v3.Document { + spec := "openapi: 3.1.0\ninfo: {title: Direction, version: 1.0.0}\npaths:\n /widgets:\n" + tc.path + + "\ncomponents:\n responses:\n Empty: {description: ok}\n pathItems:\n Empty: {}\n schemas:\n" + usageWidget(required) + info, err := datamodel.ExtractSpecInfo([]byte(spec)) + require.NoError(t, err) + config := datamodel.NewDocumentConfiguration() + config.TransformSiblingRefs = transform + doc, err := v3.CreateDocumentFromConfig(info, config) + require.NoError(t, err) + return doc + } + changes := CompareDocuments(build("name"), build("name, id")) + require.NotNil(t, changes) + for _, ch := range changes.GetAllChanges() { + if ch.Property == v3.RequiredLabel { + assert.Equal(t, tc.breaking, ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } + } +} + func TestRequiredOneOfBranchesInARequest(t *testing.T) { const widget = "{$ref: '#/components/schemas/Widget'}" for _, tc := range []struct { @@ -210,25 +359,29 @@ func TestRequiredOneOfBranchesInARequest(t *testing.T) { // widgetUsage returns the direction of Widget in a document whose only response schema is the given YAML. The second // result is false when the usage of the document is unknown. func TestSchemaUsageOneOfBranchesWithAReferenceThatIsAnAlias(t *testing.T) { - // The model does not resolve a $ref whose value is an alias, so it cannot tell what such a branch accepts. + // The model does not resolve a $ref whose value is an alias, so it cannot tell what such a branch accepts, and + // the walk following such a $ref elsewhere reaches what the model does not. Both keep the union shared, as before. const widget = "{$ref: '#/components/schemas/Widget'}" + const others = "\n /others: {get: {responses: {'200': {description: ok, content: {application/json: {schema: {$ref: *other}}}}}}}" for _, tc := range []struct { - name, schema string - direction schemaDirection + name, schema, paths string + direction schemaDirection }{ - {"branch that is such a reference", "{oneOf: [" + widget + ", {$ref: *text}]}", sharedSchema}, - {"no such reference", "{oneOf: [" + widget + ", {type: string}]}", responseSchema}, + {"branch that is such a reference", "{oneOf: [" + widget + ", {$ref: *text}]}", "", sharedSchema}, + {"such a reference elsewhere", "{oneOf: [" + widget + ", {type: string}]}", others, sharedSchema}, + {"no such reference", "{oneOf: [" + widget + ", {type: string}]}", "", responseSchema}, } { t.Run(tc.name, func(t *testing.T) { var root yaml.Node require.NoError(t, yaml.Unmarshal([]byte(`openapi: 3.1.0 -x-refs: {text: &text '#/components/schemas/Text'} +x-refs: {text: &text '#/components/schemas/Text', other: &other '#/components/schemas/Other'} paths: - /widgets: {get: {responses: {'200': {description: ok, content: {application/json: {schema: `+tc.schema+`}}}}}} + /widgets: {get: {responses: {'200': {description: ok, content: {application/json: {schema: `+tc.schema+`}}}}}}`+tc.paths+` components: schemas: Widget: {type: object} - Text: {type: string}`), &root)) + Text: {type: string} + Other: {type: object}`), &root)) idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) usage := buildSchemaUsage(idx) require.NotNil(t, usage)