From 83a6157a96e8020e1c13aa196804e282899ee9b4 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 23 Nov 2026 15:18:28 +0100 Subject: [PATCH 01/11] fix(what-changed): follow discriminator mappings instead of dropping all usage Any discriminator reachable from a path made the usage walk give up, so every schema in the document fell back to the conservative required-entry rule, even schemas unrelated to the discriminator. The walk now follows the schemas a discriminator mapping or default mapping names, in the direction of the schema that holds it. A discriminator can also select any component schema by name, so each component schema that is already in use gains that direction as well. Schemas that nothing refers to stay unused. A mapping value that is not a schema of the document, such as a file or a URL, still makes the usage unknown. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 68 ++++++++++- .../model/schema_usage_discriminator_test.go | 107 ++++++++++++++++++ what-changed/model/schema_usage_test.go | 2 +- 3 files changed, 174 insertions(+), 3 deletions(-) create mode 100644 what-changed/model/schema_usage_discriminator_test.go diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 1d48e6b1..9ce0632f 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -106,6 +106,9 @@ type usageWalker struct { visited [schemaObject + 1]schemaUsage targets map[string]*yaml.Node unknown bool + // implicit is the direction of every schema that has a discriminator. A discriminator can select + // any component schema by name, so those schemas are used in that direction as well. + implicit schemaDirection } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -132,6 +135,7 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { w.each(value, pathItemObject, sharedSchema) } } + w.walkImplicitTargets(root) if w.unknown { return nil } @@ -265,16 +269,76 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc w.walk(value, schemaObject, sharedSchema) case v3.OneOfLabel: w.each(value, schemaObject, sharedSchema) + case v3.DiscriminatorLabel: + w.discriminator(value, sameInstance) case v3.SchemaDialectLabel: if !knownUsageDialect(value) { w.unknown = true } - case v3.DynamicRefLabel, "$recursiveRef", "$id", v3.DiscriminatorLabel: - // Resource scopes and implicit discriminator targets need more than local pointer reachability. + case v3.DynamicRefLabel, "$recursiveRef", "$id": + // Resource scopes need more than local pointer reachability. w.unknown = true } } +// discriminator follows the schemas its mapping and default mapping name, and records that any component schema can +// be selected by name. +func (w *usageWalker) discriminator(node *yaml.Node, dir schemaDirection) { + w.implicit |= dir + for key, value := range usageFields(node) { + switch key { + case base.MappingLabel: + for _, target := range usageFields(value) { + w.discriminatorTarget(target, dir) + } + case base.DefaultMappingLabel: + w.discriminatorTarget(value, dir) + } + } +} + +// discriminatorTarget follows one mapping value, which is a reference or a schema name. A value that is not a schema +// of this document, such as a file or a URL, cannot be followed. +func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) { + ref := utils.NodeAlias(value).Value + if !strings.HasPrefix(ref, "#/") { + ref = "#/components/schemas/" + ref + } + schema := w.localTarget(ref) + if schema == nil { + w.unknown = true + return + } + w.walk(schema, schemaObject, dir) +} + +// walkImplicitTargets adds the direction of each discriminator to the component schemas that are already in use. +// A schema that nothing refers to stays unused, which keeps the conservative result. +func (w *usageWalker) walkImplicitTargets(root *yaml.Node) { + if w.implicit == 0 { + return + } + var components []*yaml.Node + for key, value := range usageFields(root) { + if key != v3.ComponentsLabel { + continue + } + for name, schemas := range usageFields(value) { + if name != v3.SchemasLabel { + continue + } + for _, schema := range usageFields(schemas) { + if schema = utils.NodeAlias(schema); w.visited[schemaObject][schema] != 0 { + components = append(components, schema) + } + } + } + } + for _, schema := range components { + w.walk(schema, schemaObject, w.implicit) + } +} + // 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_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go new file mode 100644 index 00000000..1e50f06b --- /dev/null +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -0,0 +1,107 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package model + +import ( + "strings" + "testing" +) + +func TestRequiredDiscriminator(t *testing.T) { + const pets = ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'}` + const widgetRequestWithDiscriminator = ` requestBody: + content: + application/json: + schema: {type: object, discriminator: DISCRIMINATOR} + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Widget'}` + petSchemas := func(mapping string) string { + return ` + Pet: + oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Dog'}] + discriminator: {propertyName: kind, mapping: ` + mapping + `} + Cat: {type: object, properties: {kind: {type: string}}} + Dog: {type: object, properties: {kind: {type: string}}}` + } + const localMapping = "{cat: '#/components/schemas/Cat', dog: Dog}" + build := func(op, mapping, required string) string { + // A components section that is not schemas has nothing to follow. + spec := usageSpec(op, usageWidget(required)+petSchemas(mapping)+"\n responses:\n Ok: {description: ok}") + return strings.Replace(spec, "\ncomponents:", pets+"\ncomponents:", 1) + } + for _, tc := range []struct { + name, op, mapping string + breaking bool + }{ + {"unrelated response only discriminator", usageResponseOnly, localMapping, false}, + {"unrelated discriminator without a mapping", usageResponseOnly, "{}", false}, + {"widget also used by a request", usageShared, localMapping, true}, + {"widget not used at all", usageUnused, localMapping, true}, + {"mapping outside the document", usageResponseOnly, "{cat: 'https://example.com/cat.yaml#/Cat'}", true}, + {"mapping to a file", usageResponseOnly, "{cat: 'cat.yaml'}", true}, + {"mapping to a schema that does not exist", usageResponseOnly, "{ghost: Ghost}", true}, + { + "request discriminator selecting widget by name", + strings.Replace(widgetRequestWithDiscriminator, "DISCRIMINATOR", "{propertyName: kind}", 1), localMapping, true, + }, + { + "request discriminator mapping to widget", + strings.Replace(widgetRequestWithDiscriminator, "DISCRIMINATOR", "{propertyName: kind, mapping: {w: '#/components/schemas/Widget'}}", 1), localMapping, true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + requireEntryBreaking(t, build(tc.op, tc.mapping, "name"), build(tc.op, tc.mapping, "name, id"), tc.breaking) + }) + } +} + +func TestRequiredDiscriminatorTargetOnlyUsedByResponse(t *testing.T) { + // Dog is only reachable through the discriminator that a response uses. + const spec = `openapi: 3.1.0 +info: {title: Direction, version: 1.0.0} +paths: + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'} +components: + schemas: + Pet: + type: object + discriminator: DISCRIMINATOR + Dog: {type: object, required: [kind], properties: {kind: {type: string}, name: {type: string}}}` + for _, tc := range []struct { + name, discriminator string + breaking bool + }{ + {"mapping by reference", "{propertyName: kind, mapping: {dog: '#/components/schemas/Dog'}}", false}, + {"mapping by name", "{propertyName: kind, mapping: {dog: Dog}}", false}, + {"default mapping by reference", "{propertyName: kind, defaultMapping: '#/components/schemas/Dog'}", false}, + {"default mapping by name", "{propertyName: kind, defaultMapping: Dog}", false}, + {"mapping and default mapping", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: Dog}", false}, + {"default mapping outside the document", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: 'other.yaml'}", true}, + {"default mapping to a schema that does not exist", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: Ghost}", true}, + } { + t.Run(tc.name, func(t *testing.T) { + old := strings.Replace(spec, "DISCRIMINATOR", tc.discriminator, 1) + requireEntryBreaking(t, old, strings.Replace(old, "required: [kind]", "required: [kind, name]", 1), tc.breaking) + }) + } +} diff --git a/what-changed/model/schema_usage_test.go b/what-changed/model/schema_usage_test.go index c20977e1..fee64600 100644 --- a/what-changed/model/schema_usage_test.go +++ b/what-changed/model/schema_usage_test.go @@ -203,7 +203,7 @@ func TestRequiredConservativeSchemaContexts(t *testing.T) { {"literal reference in example", "allOf: [" + ref + "], example: {$ref: '#/components/schemas/Widget'}", false}, {"dynamic reference", "allOf: [" + ref + ", {$dynamicRef: '#fallback'}]", true}, {"resource scoped pointer", "$id: 'https://example.com/model', allOf: [" + ref + "]", true}, - {"discriminator", "allOf: [" + ref + "], discriminator: {propertyName: kind}", true}, + {"discriminator", "allOf: [" + ref + "], discriminator: {propertyName: kind}", false}, } { t.Run(tc.name, func(t *testing.T) { op := strings.Replace(usageResponseOnly, ref, "{"+tc.wrapper+"}", 1) From 92482b88e6a62088ed92a7f7a381258622a2a080 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 23 Nov 2026 15:18:28 +0100 Subject: [PATCH 02/11] fix(what-changed): give every component schema the discriminator direction A discriminator can select any component schema by name, including one that nothing refers to. The second pass only walked component schemas that were already in use, so a schema below an unused component kept the direction of the place that referred to it. With a request-side discriminator, a schema used by a response inside such a component could be relaxed although a request can send it. The second pass now walks every component schema with the direction of the discriminators. A walk can reach another discriminator and add a direction, so it repeats until the directions stop changing. A schema that only a discriminator can select is now used in that direction instead of not at all. A mapping value that is neither a reference nor a component name is a relative URI of another document, so it now makes the usage unknown instead of being resolved as a pointer inside the components. Tests cover a schema below an unused component, a mapping to an inline schema, discriminators under not and if, in a callback, in a webhook and next to unevaluatedProperties, a second discriminator found in an unused component, the removal of a required entry from a request, and a mapping to a relative path. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 48 +++--- .../model/schema_usage_discriminator_test.go | 143 +++++++++++++++++- 2 files changed, 161 insertions(+), 30 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 9ce0632f..e59b35f0 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -6,6 +6,7 @@ package model import ( "context" "iter" + "regexp" "strings" "sync" @@ -107,7 +108,7 @@ type usageWalker struct { targets map[string]*yaml.Node unknown bool // implicit is the direction of every schema that has a discriminator. A discriminator can select - // any component schema by name, so those schemas are used in that direction as well. + // any component schema by name, so every component schema is used in that direction as well. implicit schemaDirection } @@ -297,11 +298,18 @@ func (w *usageWalker) discriminator(node *yaml.Node, dir schemaDirection) { } } +// componentName is the pattern of a component name, so a mapping value that does not match it is a relative URI. +var componentName = regexp.MustCompile(`^[a-zA-Z0-9.\-_]+$`) + // discriminatorTarget follows one mapping value, which is a reference or a schema name. A value that is not a schema // of this document, such as a file or a URL, cannot be followed. func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) { ref := utils.NodeAlias(value).Value if !strings.HasPrefix(ref, "#/") { + if !componentName.MatchString(ref) { + w.unknown = true + return + } ref = "#/components/schemas/" + ref } schema := w.localTarget(ref) @@ -312,31 +320,27 @@ func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) w.walk(schema, schemaObject, dir) } -// walkImplicitTargets adds the direction of each discriminator to the component schemas that are already in use. -// A schema that nothing refers to stays unused, which keeps the conservative result. +// walkImplicitTargets gives every component schema the direction of each discriminator, because a discriminator can +// select any of them by name, including one that nothing refers to. Walking a schema can reach another discriminator +// and add a direction, so it repeats until the directions stop changing. func (w *usageWalker) walkImplicitTargets(root *yaml.Node) { - if w.implicit == 0 { - return - } - var components []*yaml.Node - for key, value := range usageFields(root) { - if key != v3.ComponentsLabel { - continue - } - for name, schemas := range usageFields(value) { - if name != v3.SchemasLabel { - continue - } - for _, schema := range usageFields(schemas) { - if schema = utils.NodeAlias(schema); w.visited[schemaObject][schema] != 0 { - components = append(components, schema) - } - } + schemas := usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel) + for walked := schemaDirection(0); w.implicit != walked; { + walked = w.implicit + for _, schema := range usageFields(schemas) { + w.walk(schema, schemaObject, walked) } } - for _, schema := range components { - w.walk(schema, schemaObject, w.implicit) +} + +// 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. diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 1e50f06b..0b3c0a35 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -38,8 +38,7 @@ func TestRequiredDiscriminator(t *testing.T) { } const localMapping = "{cat: '#/components/schemas/Cat', dog: Dog}" build := func(op, mapping, required string) string { - // A components section that is not schemas has nothing to follow. - spec := usageSpec(op, usageWidget(required)+petSchemas(mapping)+"\n responses:\n Ok: {description: ok}") + spec := usageSpec(op, usageWidget(required)+petSchemas(mapping)) return strings.Replace(spec, "\ncomponents:", pets+"\ncomponents:", 1) } for _, tc := range []struct { @@ -49,18 +48,17 @@ func TestRequiredDiscriminator(t *testing.T) { {"unrelated response only discriminator", usageResponseOnly, localMapping, false}, {"unrelated discriminator without a mapping", usageResponseOnly, "{}", false}, {"widget also used by a request", usageShared, localMapping, true}, - {"widget not used at all", usageUnused, localMapping, true}, + // Only the response discriminator can select Widget, by name, so only that response uses it. + {"widget only reachable through the discriminator", usageUnused, localMapping, false}, {"mapping outside the document", usageResponseOnly, "{cat: 'https://example.com/cat.yaml#/Cat'}", true}, {"mapping to a file", usageResponseOnly, "{cat: 'cat.yaml'}", true}, {"mapping to a schema that does not exist", usageResponseOnly, "{ghost: Ghost}", true}, + // A mapping value that is not a schema name is a relative URI of another document. + {"mapping to a relative path", usageResponseOnly, "{dog: 'Dog/properties/kind'}", true}, { "request discriminator selecting widget by name", strings.Replace(widgetRequestWithDiscriminator, "DISCRIMINATOR", "{propertyName: kind}", 1), localMapping, true, }, - { - "request discriminator mapping to widget", - strings.Replace(widgetRequestWithDiscriminator, "DISCRIMINATOR", "{propertyName: kind, mapping: {w: '#/components/schemas/Widget'}}", 1), localMapping, true, - }, } { t.Run(tc.name, func(t *testing.T) { requireEntryBreaking(t, build(tc.op, tc.mapping, "name"), build(tc.op, tc.mapping, "name, id"), tc.breaking) @@ -69,7 +67,7 @@ func TestRequiredDiscriminator(t *testing.T) { } func TestRequiredDiscriminatorTargetOnlyUsedByResponse(t *testing.T) { - // Dog is only reachable through the discriminator that a response uses. + // Dog is only reachable through the discriminator that a response uses, by name or through its mapping. const spec = `openapi: 3.1.0 info: {title: Direction, version: 1.0.0} paths: @@ -105,3 +103,132 @@ components: }) } } + +func TestRequiredDiscriminatorMappingToAnInlineSchema(t *testing.T) { + // The request discriminator maps to the inline response schema, so a request can use it too. + const spec = `openapi: 3.1.0 +info: {title: Direction, version: 1.0.0} +paths: + /widgets: + post: + requestBody: + content: + application/json: + schema: + type: object + discriminator: + propertyName: kind + mapping: {w: '#/paths/~1widgets/post/responses/200/content/application~1json/schema'} + responses: + '200': + description: ok + content: + application/json: + schema: {type: object, required: [name], properties: {name: {type: string}, id: {type: string}}}` + requireEntryBreaking(t, spec, strings.Replace(spec, "required: [name]", "required: [name, id]", 1), true) +} + +func TestRequiredDiscriminatorWithoutAKnownDirection(t *testing.T) { + // Widget is only used by the /widgets response. Each case adds a discriminator that can select Widget by name + // from a request, or from a place whose direction is not known, so the required entry must stay breaking. + const pet = "{type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" + pets := func(schema string) string { + return ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: ` + schema + } + const callback = ` + /pets: + post: + responses: + '204': {description: ok} + callbacks: + done: + '{$request.body#/url}': + post: + requestBody: + content: + application/json: + schema: ` + pet + ` + responses: + '204': {description: ok}` + const webhook = ` +webhooks: + incoming: + post: + requestBody: + content: + application/json: + schema: ` + pet + ` + responses: + '204': {description: ok}` + for _, tc := range []struct{ name, paths, schemas, webhooks string }{ + {"under not", pets("{not: " + pet + "}"), "", ""}, + {"under if", pets("{if: " + pet + ", then: {type: object}}"), "", ""}, + {"holder with unevaluated properties", pets("{type: object, unevaluatedProperties: false, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}"), "", ""}, + {"in a callback", callback, "", ""}, + {"in a webhook", "", "", webhook}, + // Walking a schema that nothing refers to finds a second discriminator, which adds a direction. + {"in a schema that nothing refers to", pets(pet), "\n Odd: {not: " + pet + "}", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + build := func(required string) string { + spec := usageSpec(usageResponseOnly, usageWidget(required)+tc.schemas) + return strings.Replace(spec, "\ncomponents:", tc.paths+"\ncomponents:", 1) + tc.webhooks + } + requireEntryBreaking(t, build("name"), build("name, id"), true) + }) + } +} + +func TestRequiredDiscriminatorSelectsASchemaThatNothingRefersTo(t *testing.T) { + // Nothing refers to Widget, but the request discriminator can select it by name, and the response uses a schema + // inside it. A request can therefore send that schema as well. + const spec = `openapi: 3.1.0 +info: {title: Direction, version: 1.0.0} +paths: + /pets: + post: + requestBody: + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'} + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Widget/properties/part'} +components: + schemas: + Pet: {type: object, required: [kind], properties: {kind: {type: string}}, discriminator: {propertyName: kind}} + Widget: + allOf: [{$ref: '#/components/schemas/Pet'}] + properties: + part: {type: object, required: [name], properties: {name: {type: string}, id: {type: string}}}` + requireEntryBreaking(t, spec, strings.Replace(spec, "required: [name]", "required: [name, id]", 1), true) +} + +func TestRequiredDiscriminatorRemovalFromARequest(t *testing.T) { + // Widget is only used by a request, but a response discriminator can select it by name, so removing a required + // entry, which is only safe for a request, must stay breaking. + const pets = ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}` + build := func(required string) string { + return strings.Replace(usageSpec(usageRequestOnly, usageWidget(required)), "\ncomponents:", pets+"\ncomponents:", 1) + } + requireEntryBreaking(t, build("name, id"), build("name"), true) +} From d8120ebd143e529b4f728d60744cfd9e4f03d9d1 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 10:51:08 +0100 Subject: [PATCH 03/11] fix(what-changed): only select the children of a parent discriminator by name Every component schema got the direction of each discriminator, because one can select a schema by its name. The OpenAPI specification is narrower: next to a oneOf or an anyOf, all possible schemas must be listed, and only a discriminator on a parent schema can select a schema that builds on it with allOf. So a schema that nothing uses, and that a oneOf does not list, was treated as used by the response, and a required entry added to it was no longer breaking. A discriminator next to a oneOf or an anyOf now only selects the listed schemas, which the walk follows already. A discriminator on a parent selects the component schemas that build on the parent with allOf, directly, through other schemas, through a reference or in a nested allOf. A reference that cannot be followed while looking for them could lead to the parent, so it makes the usage unknown. The tests that relied on any schema being selectable by name now let Widget build on the parent. New tests cover a schema the union does not list, a union next to a parent that has a child, the ways a child can build on a parent, a schema that builds on itself, and references that cannot be followed. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 84 ++++++--- .../model/schema_usage_discriminator_test.go | 171 ++++++++++++++++-- 2 files changed, 214 insertions(+), 41 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index e59b35f0..e88e97bb 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -107,9 +107,11 @@ type usageWalker struct { visited [schemaObject + 1]schemaUsage targets map[string]*yaml.Node unknown bool - // implicit is the direction of every schema that has a discriminator. A discriminator can select - // any component schema by name, so every component schema is used in that direction as well. - implicit schemaDirection + // schemas are the component schemas, which a discriminator can select by name. + schemas *yaml.Node + // children lists, for each schema, the component schemas that build on it with allOf, directly or through other + // schemas. It is built for the first discriminator that needs it. + children map[*yaml.Node][]*yaml.Node } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -120,7 +122,11 @@ 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)} + w := usageWalker{ + index: idx, + targets: make(map[string]*yaml.Node), + schemas: usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel), + } for i := range w.visited { w.visited[i] = make(schemaUsage) } @@ -136,7 +142,6 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { w.each(value, pathItemObject, sharedSchema) } } - w.walkImplicitTargets(root) if w.unknown { return nil } @@ -232,7 +237,7 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect w.walk(value, payloadObject, dir) } case schemaObject: - w.schemaField(key, value, dir, sameInstance) + w.schemaField(node, key, value, dir, sameInstance) } } } @@ -254,7 +259,7 @@ func (w *usageWalker) operationField(key string, value *yaml.Node, inherited sch } } -func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstance schemaDirection) { +func (w *usageWalker) schemaField(node *yaml.Node, key string, value *yaml.Node, dir, sameInstance schemaDirection) { switch key { case v3.AllOfLabel, v3.AnyOfLabel, v3.DependentSchemasLabel: w.each(value, schemaObject, sameInstance) @@ -271,7 +276,7 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc case v3.OneOfLabel: w.each(value, schemaObject, sharedSchema) case v3.DiscriminatorLabel: - w.discriminator(value, sameInstance) + w.discriminator(node, value, sameInstance) case v3.SchemaDialectLabel: if !knownUsageDialect(value) { w.unknown = true @@ -282,10 +287,10 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc } } -// discriminator follows the schemas its mapping and default mapping name, and records that any component schema can -// be selected by name. -func (w *usageWalker) discriminator(node *yaml.Node, dir schemaDirection) { - w.implicit |= dir +// discriminator follows the schemas its mapping and default mapping name. Next to a oneOf or an anyOf it can only +// select one of the listed schemas, which the walk follows already. Otherwise it is on a parent schema, and can +// select any component schema that builds on the parent with allOf by name. +func (w *usageWalker) discriminator(holder, node *yaml.Node, dir schemaDirection) { for key, value := range usageFields(node) { switch key { case base.MappingLabel: @@ -296,6 +301,14 @@ func (w *usageWalker) discriminator(node *yaml.Node, dir schemaDirection) { w.discriminatorTarget(value, dir) } } + for key := range usageFields(holder) { + if key == v3.OneOfLabel || key == v3.AnyOfLabel { + return + } + } + for _, child := range w.allOfChildren(holder) { + w.walk(child, schemaObject, dir) + } } // componentName is the pattern of a component name, so a mapping value that does not match it is a relative URI. @@ -320,15 +333,44 @@ func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) w.walk(schema, schemaObject, dir) } -// walkImplicitTargets gives every component schema the direction of each discriminator, because a discriminator can -// select any of them by name, including one that nothing refers to. Walking a schema can reach another discriminator -// and add a direction, so it repeats until the directions stop changing. -func (w *usageWalker) walkImplicitTargets(root *yaml.Node) { - schemas := usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel) - for walked := schemaDirection(0); w.implicit != walked; { - walked = w.implicit - for _, schema := range usageFields(schemas) { - w.walk(schema, schemaObject, walked) +// allOfChildren returns the component schemas that build on parent with allOf, directly or through other schemas. +func (w *usageWalker) allOfChildren(parent *yaml.Node) []*yaml.Node { + if w.children == nil { + w.children = make(map[*yaml.Node][]*yaml.Node) + for _, schema := range usageFields(w.schemas) { + schema = utils.NodeAlias(schema) + ancestors := make(map[*yaml.Node]bool) + w.ancestors(schema, ancestors) + for ancestor := range ancestors { + w.children[ancestor] = append(w.children[ancestor], schema) + } + } + } + return w.children[parent] +} + +// ancestors collects node and the schemas it builds on with allOf. A schema with a $ref builds on the schema it refers +// to as well, so the references are followed too. A reference that cannot be followed could lead to a parent, so it +// makes the usage unknown. +func (w *usageWalker) ancestors(node *yaml.Node, seen map[*yaml.Node]bool) { + node = utils.NodeAlias(node) + if node == nil || seen[node] { + return + } + seen[node] = true + for key, value := range usageFields(node) { + switch key { + case v3.RefLabel: + target := w.localTarget(utils.NodeAlias(value).Value) + if target == nil { + w.unknown = true + return + } + w.ancestors(target, seen) + case v3.AllOfLabel: + for _, item := range utils.NodeAlias(value).Content { + w.ancestors(item, seen) + } } } } diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 0b3c0a35..67d1933e 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -6,6 +6,11 @@ package model import ( "strings" "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/index" + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" ) func TestRequiredDiscriminator(t *testing.T) { @@ -21,7 +26,7 @@ func TestRequiredDiscriminator(t *testing.T) { const widgetRequestWithDiscriminator = ` requestBody: content: application/json: - schema: {type: object, discriminator: DISCRIMINATOR} + schema: SCHEMA responses: '200': description: ok @@ -48,16 +53,24 @@ func TestRequiredDiscriminator(t *testing.T) { {"unrelated response only discriminator", usageResponseOnly, localMapping, false}, {"unrelated discriminator without a mapping", usageResponseOnly, "{}", false}, {"widget also used by a request", usageShared, localMapping, true}, - // Only the response discriminator can select Widget, by name, so only that response uses it. - {"widget only reachable through the discriminator", usageUnused, localMapping, false}, + // Pet only lists Cat and Dog, so its discriminator cannot select Widget, which nothing else uses. + {"widget that the union does not list", usageUnused, localMapping, true}, {"mapping outside the document", usageResponseOnly, "{cat: 'https://example.com/cat.yaml#/Cat'}", true}, {"mapping to a file", usageResponseOnly, "{cat: 'cat.yaml'}", true}, {"mapping to a schema that does not exist", usageResponseOnly, "{ghost: Ghost}", true}, // A mapping value that is not a schema name is a relative URI of another document. {"mapping to a relative path", usageResponseOnly, "{dog: 'Dog/properties/kind'}", true}, { - "request discriminator selecting widget by name", - strings.Replace(widgetRequestWithDiscriminator, "DISCRIMINATOR", "{propertyName: kind}", 1), localMapping, true, + "request discriminator next to a oneOf that does not list widget", + strings.Replace(widgetRequestWithDiscriminator, "SCHEMA", "{oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Dog'}], discriminator: {propertyName: kind}}", 1), localMapping, false, + }, + { + "request discriminator next to an anyOf that does not list widget", + strings.Replace(widgetRequestWithDiscriminator, "SCHEMA", "{anyOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Dog'}], discriminator: {propertyName: kind}}", 1), localMapping, false, + }, + { + "request discriminator on a parent that widget does not build on", + strings.Replace(widgetRequestWithDiscriminator, "SCHEMA", "{type: object, discriminator: {propertyName: kind}}", 1), localMapping, false, }, } { t.Run(tc.name, func(t *testing.T) { @@ -129,9 +142,11 @@ paths: } func TestRequiredDiscriminatorWithoutAKnownDirection(t *testing.T) { - // Widget is only used by the /widgets response. Each case adds a discriminator that can select Widget by name - // from a request, or from a place whose direction is not known, so the required entry must stay breaking. - const pet = "{type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" + // Widget is only used by the /widgets response, and builds on Pet with allOf. Each case uses Pet, which holds a + // discriminator, from a request or from a place whose direction is not known, so Pet can select Widget by name + // from there and the required entry must stay breaking. + const pet = "{$ref: '#/components/schemas/Pet'}" + const petSchema = "\n Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" pets := func(schema string) string { return ` /pets: @@ -169,17 +184,19 @@ webhooks: responses: '204': {description: ok}` for _, tc := range []struct{ name, paths, schemas, webhooks string }{ - {"under not", pets("{not: " + pet + "}"), "", ""}, - {"under if", pets("{if: " + pet + ", then: {type: object}}"), "", ""}, - {"holder with unevaluated properties", pets("{type: object, unevaluatedProperties: false, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}"), "", ""}, - {"in a callback", callback, "", ""}, - {"in a webhook", "", "", webhook}, - // Walking a schema that nothing refers to finds a second discriminator, which adds a direction. - {"in a schema that nothing refers to", pets(pet), "\n Odd: {not: " + pet + "}", ""}, + {"under not", pets("{not: " + pet + "}"), petSchema, ""}, + {"under if", pets("{if: " + pet + ", then: {type: object}}"), petSchema, ""}, + {"holder with unevaluated properties", pets(pet), "\n Pet: {type: object, unevaluatedProperties: false, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}", ""}, + {"in a callback", callback, petSchema, ""}, + {"in a webhook", "", petSchema, webhook}, + // Walking a child of the response parent Base finds Pet under not. + {"in a child of another parent", pets("{$ref: '#/components/schemas/Base'}"), petSchema + ` + Base: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}} + Kid: {allOf: [{$ref: '#/components/schemas/Base'}], properties: {odd: {not: ` + pet + `}}}`, ""}, } { t.Run(tc.name, func(t *testing.T) { build := func(required string) string { - spec := usageSpec(usageResponseOnly, usageWidget(required)+tc.schemas) + spec := usageSpec(usageResponseOnly, usageChild(required, "allOf: ["+pet+"]")+tc.schemas) return strings.Replace(spec, "\ncomponents:", tc.paths+"\ncomponents:", 1) + tc.webhooks } requireEntryBreaking(t, build("name"), build("name, id"), true) @@ -187,6 +204,117 @@ webhooks: } } +func TestRequiredDiscriminatorParent(t *testing.T) { + // A request sends Base, which holds a discriminator, and the /widgets response uses Widget. Base can select any + // component schema that builds on it with allOf by name, so a request can send that schema as well. + const bases = ` + /bases: + post: + requestBody: + content: + application/json: + schema: {$ref: '#/components/schemas/Base'} + responses: + '204': {description: ok}` + const base = ` + Base: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}` + for _, tc := range []struct { + name, builds, schemas string + breaking bool + }{ + {"widget builds on base", "allOf: [{$ref: '#/components/schemas/Base'}]", "", true}, + {"widget builds on base through another child", "allOf: [{$ref: '#/components/schemas/Mid'}]", "\n Mid: {allOf: [{$ref: '#/components/schemas/Base'}]}", true}, + {"widget builds on base through a reference", "allOf: [{$ref: '#/components/schemas/Alias'}]", "\n Alias: {$ref: '#/components/schemas/Base'}", true}, + {"widget builds on base in a nested allOf", "allOf: [{allOf: [{$ref: '#/components/schemas/Base'}]}]", "", true}, + {"widget does not build on base", "", "", false}, + {"schema that builds on itself", "", "\n Loop: {allOf: [{$ref: '#/components/schemas/Loop'}, {$ref: '#/components/schemas/Base'}]}", false}, + } { + t.Run(tc.name, func(t *testing.T) { + build := func(required string) string { + spec := usageSpec(usageResponseOnly, usageChild(required, tc.builds)+base+tc.schemas) + return strings.Replace(spec, "\ncomponents:", bases+"\ncomponents:", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), tc.breaking) + }) + } +} + +func TestRequiredDiscriminatorNextToAUnionSelectsNoChild(t *testing.T) { + // A request sends Base, and Widget builds on it with allOf. Next to a oneOf or an anyOf, the discriminator can + // only select the listed Cat, so Widget stays only used by the /widgets response. + const bases = ` + /bases: + post: + requestBody: + content: + application/json: + schema: {$ref: '#/components/schemas/Base'} + responses: + '204': {description: ok}` + for _, union := range []string{"oneOf", "anyOf"} { + t.Run(union, func(t *testing.T) { + schemas := ` + Base: {` + union + `: [{$ref: '#/components/schemas/Cat'}], discriminator: {propertyName: kind}} + Cat: {type: object, properties: {kind: {type: string}}}` + build := func(required string) string { + spec := usageSpec(usageResponseOnly, usageChild(required, "allOf: [{$ref: '#/components/schemas/Base'}]")+schemas) + return strings.Replace(spec, "\ncomponents:", bases+"\ncomponents:", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), false) + }) + } +} + +func TestRequiredDiscriminatorChildOfAResponseParent(t *testing.T) { + // Nothing refers to Widget, but it builds on Pet, which only a response uses, so only that response can select it. + const pets = ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'}` + const pet = ` + Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}` + build := func(required string) string { + spec := usageSpec(usageUnused, usageChild(required, "allOf: [{$ref: '#/components/schemas/Pet'}]")+pet) + return strings.Replace(spec, "\ncomponents:", pets+"\ncomponents:", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), false) +} + +func TestSchemaUsageDiscriminatorParentWithUnresolvedReferences(t *testing.T) { + // The schema behind a reference that cannot be followed could build on Base, so Base could select Remote. + for _, tc := range []struct { + ref string + known bool + }{ + {"#/components/schemas/Base", true}, + {"other.yaml#/Base", false}, + {"#/components/schemas/Missing", false}, + } { + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`paths: + /bases: {post: {requestBody: {content: {application/json: {schema: {$ref: '#/components/schemas/Base'}}}}}} +components: + schemas: + Base: {type: object, discriminator: {propertyName: kind}} + Remote: {allOf: [{$ref: '`+tc.ref+`'}]}`), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + assert.Equal(t, tc.known, buildSchemaUsage(idx) != nil, tc.ref) + } +} + +// usageChild is Widget with the keyword that makes it build on another schema, or without one when builds is empty. +func usageChild(required, builds string) string { + if builds == "" { + return usageWidget(required) + } + return strings.Replace(usageWidget(required), " Widget:\n", " Widget:\n "+builds+"\n", 1) +} + func TestRequiredDiscriminatorSelectsASchemaThatNothingRefersTo(t *testing.T) { // Nothing refers to Widget, but the request discriminator can select it by name, and the response uses a schema // inside it. A request can therefore send that schema as well. @@ -216,8 +344,8 @@ components: } func TestRequiredDiscriminatorRemovalFromARequest(t *testing.T) { - // Widget is only used by a request, but a response discriminator can select it by name, so removing a required - // entry, which is only safe for a request, must stay breaking. + // Widget is only used by a request, but it builds on Pet, so the response discriminator on Pet can select it by + // name. Removing a required entry, which is only safe for a request, must stay breaking. const pets = ` /pets: get: @@ -226,9 +354,12 @@ func TestRequiredDiscriminatorRemovalFromARequest(t *testing.T) { description: ok content: application/json: - schema: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}` + schema: {$ref: '#/components/schemas/Pet'}` + const pet = ` + Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}` build := func(required string) string { - return strings.Replace(usageSpec(usageRequestOnly, usageWidget(required)), "\ncomponents:", pets+"\ncomponents:", 1) + spec := usageSpec(usageRequestOnly, usageChild(required, "allOf: [{$ref: '#/components/schemas/Pet'}]")+pet) + return strings.Replace(spec, "\ncomponents:", pets+"\ncomponents:", 1) } requireEntryBreaking(t, build("name, id"), build("name"), true) } From afe5806f52c76ba276a984bb157943f194d37f08 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 10:52:09 +0100 Subject: [PATCH 04/11] fix(what-changed): treat a discriminator mapping to a value that is not a schema as unknown A mapping or default mapping value such as '#/info/title' resolves to a string. The walk skips anything that is not a mapping, so the discriminator target was silently dropped while the rest of the usage was kept. A target that is neither a mapping nor a boolean schema now makes the usage unknown. A boolean schema has nothing to walk, so it stays a valid target. Tests cover a string target in mapping and, in OpenAPI 3.2, in defaultMapping, and a boolean schema in both. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 3 +- .../model/schema_usage_discriminator_test.go | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index e88e97bb..7e39a113 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -326,7 +326,8 @@ func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) ref = "#/components/schemas/" + ref } schema := w.localTarget(ref) - if schema == nil { + // A pointer can lead to a value that cannot be a schema, such as a string. A boolean schema has nothing to walk. + if schema == nil || (utils.NodeAlias(schema).Kind != yaml.MappingNode && !utils.IsNodeBoolValue(schema)) { w.unknown = true return } diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 67d1933e..558faea2 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -117,6 +117,43 @@ components: } } +func TestRequiredDiscriminatorTargetThatIsNotASchema(t *testing.T) { + // Dog is only reachable through the discriminator that a response uses. A pointer to a value that cannot be a + // schema cannot be followed, so the usage is unknown. A boolean schema can be a target. + const spec = `openapi: VERSION +info: {title: Direction, version: 1.0.0} +paths: + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'} +components: + schemas: + Pet: + type: object + discriminator: DISCRIMINATOR + Dog: {type: object, required: [kind], properties: {kind: {type: string}, name: {type: string}}} + Anything: true` + for _, tc := range []struct { + name, version, discriminator string + breaking bool + }{ + {"mapping to a string", "3.1.0", "{propertyName: kind, mapping: {dog: Dog, title: '#/info/title'}}", true}, + {"default mapping to a string", "3.2.0", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: '#/info/title'}", true}, + {"mapping to a boolean schema", "3.1.0", "{propertyName: kind, mapping: {dog: Dog, any: Anything}}", false}, + {"default mapping to a boolean schema", "3.2.0", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: '#/components/schemas/Anything'}", false}, + } { + t.Run(tc.name, func(t *testing.T) { + old := strings.NewReplacer("VERSION", tc.version, "DISCRIMINATOR", tc.discriminator).Replace(spec) + requireEntryBreaking(t, old, strings.Replace(old, "required: [kind]", "required: [kind, name]", 1), tc.breaking) + }) + } +} + func TestRequiredDiscriminatorMappingToAnInlineSchema(t *testing.T) { // The request discriminator maps to the inline response schema, so a request can use it too. const spec = `openapi: 3.1.0 From c230230ed30123937c89d2230668e16559400897 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 26 Nov 2026 10:53:30 +0100 Subject: [PATCH 05/11] perf(what-changed): stop resolving discriminator targets once the usage is unknown A mapping value outside the document makes the usage unknown, so the result is dropped. The walker still resolved and cached every mapping value after it and the default mapping, built the index of children for a parent discriminator, and kept following the references of other component schemas after one of them could not be followed. Each of these now stops as soon as the usage is unknown. A test checks that no target is resolved after the usage becomes unknown, both from a mapping value and while looking for the children of a parent. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 9 ++++- .../model/schema_usage_discriminator_test.go | 33 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 7e39a113..ed9dec6e 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -301,6 +301,9 @@ func (w *usageWalker) discriminator(holder, node *yaml.Node, dir schemaDirection w.discriminatorTarget(value, dir) } } + if w.unknown { + return + } for key := range usageFields(holder) { if key == v3.OneOfLabel || key == v3.AnyOfLabel { return @@ -317,6 +320,10 @@ var componentName = regexp.MustCompile(`^[a-zA-Z0-9.\-_]+$`) // discriminatorTarget follows one mapping value, which is a reference or a schema name. A value that is not a schema // of this document, such as a file or a URL, cannot be followed. func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) { + // The usage is dropped once it is unknown, so the other targets do not need to be resolved. + if w.unknown { + return + } ref := utils.NodeAlias(value).Value if !strings.HasPrefix(ref, "#/") { if !componentName.MatchString(ref) { @@ -355,7 +362,7 @@ func (w *usageWalker) allOfChildren(parent *yaml.Node) []*yaml.Node { // makes the usage unknown. func (w *usageWalker) ancestors(node *yaml.Node, seen map[*yaml.Node]bool) { node = utils.NodeAlias(node) - if node == nil || seen[node] { + if w.unknown || node == nil || seen[node] { return } seen[node] = true diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 558faea2..55eb2caa 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/pb33f/go-yaml" + v3 "github.com/pb33f/libopenapi/datamodel/low/v3" "github.com/pb33f/libopenapi/index" "github.com/pb33f/testify/assert" "github.com/pb33f/testify/require" @@ -344,6 +345,38 @@ components: } } +func TestSchemaUsageDiscriminatorStopsOnceUnknown(t *testing.T) { + // The first mapping value makes the usage unknown, so the usage is dropped and nothing else is resolved: not the + // other mapping values, the default mapping, the children of Pet, or the schemas Cat and Dog build on. + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`components: + schemas: + Pet: + type: object + discriminator: + propertyName: kind + mapping: {remote: 'https://example.com/cat.yaml', cat: Cat, dog: '#/components/schemas/Dog'} + defaultMapping: Cat + Remote: {allOf: [{$ref: 'other.yaml#/Pet'}]} + Cat: {allOf: [{$ref: '#/components/schemas/Pet'}]} + Dog: {allOf: [{$ref: '#/components/schemas/Pet'}]}`), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + schemas := usageField(usageField(root.Content[0], v3.ComponentsLabel), v3.SchemasLabel) + pet := usageField(schemas, "Pet") + + w := usageWalker{index: idx, targets: make(map[string]*yaml.Node), schemas: schemas} + w.discriminator(pet, usageField(pet, v3.DiscriminatorLabel), responseSchema) + assert.True(t, w.unknown) + assert.Empty(t, w.targets) + assert.Nil(t, w.children) + + // Remote makes the usage unknown while looking for the children, so the references of Cat and Dog are not resolved. + w = usageWalker{index: idx, targets: make(map[string]*yaml.Node), schemas: schemas} + w.allOfChildren(pet) + assert.True(t, w.unknown) + assert.Empty(t, w.targets) +} + // usageChild is Widget with the keyword that makes it build on another schema, or without one when builds is empty. func usageChild(required, builds string) string { if builds == "" { From 013e41885f852ea4da6e1c9133fbd48169cf8658 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 15:18:01 +0100 Subject: [PATCH 06/11] fix(what-changed): only read an allOf next to a $ref as a parent when the model does Looking for the children of a parent discriminator, the walker followed both a $ref and the allOf next to it. Without TransformSiblingRefs the schema model reads a schema with a $ref as the referenced schema alone, so with Alias: {$ref: Widget, allOf: [{$ref: Pet}]} the model does not make Alias build on Pet. The walk still did, so a discriminator on a response-only Pet gave Widget the response direction, and requiring a property of Widget was not breaking. An allOf next to a $ref now only counts with TransformSiblingRefs, as in the model. The transform does not depend on the OpenAPI version. A test covers that fixture with the transform on, where it stays not breaking, and off, where it is now breaking. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 20 +++++---- .../model/schema_usage_discriminator_test.go | 43 +++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index ed9dec6e..7d2ef023 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -109,6 +109,9 @@ type usageWalker struct { unknown bool // schemas are the component schemas, which a discriminator can select by name. schemas *yaml.Node + // refSiblings reads the keywords next to $ref, as the schema model does with TransformSiblingRefs. Without it, the + // model reads a schema with a $ref as the referenced schema alone. + refSiblings bool // children lists, for each schema, the component schemas that build on it with allOf, directly or through other // schemas. It is built for the first discriminator that needs it. children map[*yaml.Node][]*yaml.Node @@ -123,9 +126,10 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { root = root.Content[0] } w := usageWalker{ - index: idx, - targets: make(map[string]*yaml.Node), - schemas: usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel), + index: idx, + targets: make(map[string]*yaml.Node), + schemas: usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel), + refSiblings: idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, } for i := range w.visited { w.visited[i] = make(schemaUsage) @@ -358,8 +362,8 @@ func (w *usageWalker) allOfChildren(parent *yaml.Node) []*yaml.Node { } // ancestors collects node and the schemas it builds on with allOf. A schema with a $ref builds on the schema it refers -// to as well, so the references are followed too. A reference that cannot be followed could lead to a parent, so it -// makes the usage unknown. +// to as well, so the references are followed too, and an allOf next to a $ref only counts when the model reads it. A +// reference that cannot be followed could lead to a parent, so it makes the usage unknown. func (w *usageWalker) ancestors(node *yaml.Node, seen map[*yaml.Node]bool) { node = utils.NodeAlias(node) if w.unknown || node == nil || seen[node] { @@ -367,15 +371,15 @@ func (w *usageWalker) ancestors(node *yaml.Node, seen map[*yaml.Node]bool) { } seen[node] = true for key, value := range usageFields(node) { - switch key { - case v3.RefLabel: + switch { + case key == v3.RefLabel: target := w.localTarget(utils.NodeAlias(value).Value) if target == nil { w.unknown = true return } w.ancestors(target, seen) - case v3.AllOfLabel: + case key == v3.AllOfLabel && (w.refSiblings || usageField(node, v3.RefLabel) == nil): for _, item := range utils.NodeAlias(value).Content { w.ancestors(item, seen) } diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 55eb2caa..654de366 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -4,10 +4,12 @@ package model import ( + "fmt" "strings" "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" @@ -323,6 +325,47 @@ func TestRequiredDiscriminatorChildOfAResponseParent(t *testing.T) { requireEntryBreaking(t, build("name"), build("name, id"), false) } +func TestRequiredDiscriminatorChildNextToAReference(t *testing.T) { + // Nothing refers to Widget, and Alias refers to it next to an allOf with Pet, which only a response uses. With + // TransformSiblingRefs the schema model reads Alias as both, so only that response can select it. Without it, the + // model reads Alias as Widget alone, so Alias does not build on Pet and Widget stays unused. + const pets = ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'}` + const schemas = ` + Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}} + Alias: {$ref: '#/components/schemas/Widget', allOf: [{$ref: '#/components/schemas/Pet'}]}` + for _, transform := range []bool{true, false} { + t.Run(fmt.Sprintf("TransformSiblingRefs %v", transform), func(t *testing.T) { + build := func(required string) *v3.Document { + spec := usageSpec(usageUnused, usageWidget(required)+schemas) + info, err := datamodel.ExtractSpecInfo([]byte(strings.Replace(spec, "\ncomponents:", pets+"\ncomponents:", 1))) + 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, !transform, ch.Breaking) + return + } + } + t.Fatal("missing required change") + }) + } +} + func TestSchemaUsageDiscriminatorParentWithUnresolvedReferences(t *testing.T) { // The schema behind a reference that cannot be followed could build on Base, so Base could select Remote. for _, tc := range []struct { From 62e6cb785df08f1d2d24fe7286b4fe50abd05039 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 15:19:30 +0100 Subject: [PATCH 07/11] perf(what-changed): store each direct allOf link once when looking for children MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit To find the children of a parent discriminator, the walker stored every component schema under each schema it builds on, directly or through others. A chain of n schemas that each build on the one before therefore stored about n² entries: 65,536 for 256 schemas. It now stores each direct link once, from a schema to the schemas that build on it with allOf or a $ref, and follows those links from the parent when a discriminator needs its children. A set of the schemas already reached keeps cycles safe. Only the component schemas reached this way are collected and sorted by where they are declared, so a discriminator costs what its children cost, not a pass over every component schema. The children found and their order are the same as before, except that a schema listed twice under components is returned once. A test builds a chain of 256 schemas, checks that all of them are children of the first one in the order they are declared, and that 510 links are stored. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 69 ++++++++++++++----- .../model/schema_usage_discriminator_test.go | 31 +++++++++ 2 files changed, 84 insertions(+), 16 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 7d2ef023..7a35a87d 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -7,6 +7,7 @@ import ( "context" "iter" "regexp" + "slices" "strings" "sync" @@ -112,9 +113,11 @@ type usageWalker struct { // refSiblings reads the keywords next to $ref, as the schema model does with TransformSiblingRefs. Without it, the // model reads a schema with a $ref as the referenced schema alone. refSiblings bool - // children lists, for each schema, the component schemas that build on it with allOf, directly or through other - // schemas. It is built for the first discriminator that needs it. + // children lists, for each schema, the schemas that build on it directly: with allOf, or with a $ref to it. It is + // built for the first discriminator that needs it, and positions is built at the same time. children map[*yaml.Node][]*yaml.Node + // positions holds the place of each component schema, so the children are returned in the order they are declared. + positions map[*yaml.Node]int } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -345,31 +348,58 @@ func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) w.walk(schema, schemaObject, dir) } -// allOfChildren returns the component schemas that build on parent with allOf, directly or through other schemas. +// allOfChildren returns the component schemas that build on parent with allOf, directly or through other schemas, in +// the order they are declared. A parent that is a component schema is returned as well. func (w *usageWalker) allOfChildren(parent *yaml.Node) []*yaml.Node { if w.children == nil { w.children = make(map[*yaml.Node][]*yaml.Node) + w.positions = make(map[*yaml.Node]int) + linked := make(map[*yaml.Node]bool) for _, schema := range usageFields(w.schemas) { schema = utils.NodeAlias(schema) - ancestors := make(map[*yaml.Node]bool) - w.ancestors(schema, ancestors) - for ancestor := range ancestors { - w.children[ancestor] = append(w.children[ancestor], schema) + if _, seen := w.positions[schema]; !seen { + w.positions[schema] = len(w.positions) } + w.link(schema, linked) } } - return w.children[parent] + // Each direct link is stored once, so the schemas that build on parent through others are found by following them. + // Only the component schemas among them are returned, so the cost depends on the children, not on all schemas. + reached := map[*yaml.Node]bool{parent: true} + pending := []*yaml.Node{parent} + var children []*yaml.Node + if _, component := w.positions[parent]; component { + children = append(children, parent) + } + for len(pending) > 0 { + node := pending[len(pending)-1] + pending = pending[:len(pending)-1] + for _, child := range w.children[node] { + if !reached[child] { + reached[child] = true + pending = append(pending, child) + if _, component := w.positions[child]; component { + children = append(children, child) + } + } + } + } + slices.SortFunc(children, func(a, b *yaml.Node) int { + return w.positions[a] - w.positions[b] + }) + return children } -// ancestors collects node and the schemas it builds on with allOf. A schema with a $ref builds on the schema it refers -// to as well, so the references are followed too, and an allOf next to a $ref only counts when the model reads it. A -// reference that cannot be followed could lead to a parent, so it makes the usage unknown. -func (w *usageWalker) ancestors(node *yaml.Node, seen map[*yaml.Node]bool) { +// link records node as a child of the schemas it builds on with allOf, and links those schemas in turn. A schema with a +// $ref builds on the schema it refers to as well, so the references are followed too, and an allOf next to a $ref only +// counts when the model reads it. A reference that cannot be followed could lead to a parent, so it makes the usage +// unknown. +func (w *usageWalker) link(node *yaml.Node, linked map[*yaml.Node]bool) { node = utils.NodeAlias(node) - if w.unknown || node == nil || seen[node] { + if w.unknown || node == nil || linked[node] { return } - seen[node] = true + linked[node] = true for key, value := range usageFields(node) { switch { case key == v3.RefLabel: @@ -378,15 +408,22 @@ func (w *usageWalker) ancestors(node *yaml.Node, seen map[*yaml.Node]bool) { w.unknown = true return } - w.ancestors(target, seen) + w.linkParent(node, target, linked) case key == v3.AllOfLabel && (w.refSiblings || usageField(node, v3.RefLabel) == nil): for _, item := range utils.NodeAlias(value).Content { - w.ancestors(item, seen) + w.linkParent(node, item, linked) } } } } +// linkParent records child as a child of parent and links parent in turn. +func (w *usageWalker) linkParent(child, parent *yaml.Node, linked map[*yaml.Node]bool) { + parent = utils.NodeAlias(parent) + w.children[parent] = append(w.children[parent], child) + w.link(parent, linked) +} + // 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) { diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 654de366..34608d3b 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -420,6 +420,37 @@ func TestSchemaUsageDiscriminatorStopsOnceUnknown(t *testing.T) { assert.Empty(t, w.targets) } +func TestSchemaUsageDiscriminatorChildrenOfAChain(t *testing.T) { + // Each schema builds on the one before it, so every schema in the chain is a child of the first one. Storing each + // direct link once keeps the index linear in the size of the chain, instead of one entry per ancestor and child. + const length = 256 + var spec strings.Builder + spec.WriteString("components:\n schemas:\n S0: {type: object, discriminator: {propertyName: kind}}\n") + for i := 1; i < length; i++ { + fmt.Fprintf(&spec, " S%d: {allOf: [{$ref: '#/components/schemas/S%d'}]}\n", i, i-1) + } + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(spec.String()), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + schemas := usageField(usageField(root.Content[0], v3.ComponentsLabel), v3.SchemasLabel) + + w := usageWalker{index: idx, targets: make(map[string]*yaml.Node), schemas: schemas} + children := w.allOfChildren(usageField(schemas, "S0")) + assert.False(t, w.unknown) + // The children are returned in the order they are declared. + if assert.Len(t, children, length) { + for i, child := range children { + assert.Same(t, usageField(schemas, fmt.Sprintf("S%d", i)), child) + } + } + entries := 0 + for _, children := range w.children { + entries += len(children) + } + // One link from each schema to the item of its allOf, and one from that item to the schema it refers to. + assert.Equal(t, 2*(length-1), entries) +} + // usageChild is Widget with the keyword that makes it build on another schema, or without one when builds is empty. func usageChild(required, builds string) string { if builds == "" { From ba076ef0ba9db5ab24c2c55a297c9385502ad560 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 17:38:24 +0100 Subject: [PATCH 08/11] fix(what-changed): treat an allOf next to a $ref that the model reads only in place as unknown With TransformSiblingRefs, the schema model reads an allOf next to a $ref where the schema is written, but not when it reaches the schema through a $ref: it then follows the $ref of that schema and drops the rest. The sibling transform also skips an alias in a list, so an aliased schema is read the same way. While looking for the children of a parent discriminator, the walk followed that allOf in both cases. With Child: {allOf: [{$ref: Mid}, {$ref: Widget}]} and Mid: {$ref: Other, allOf: [{$ref: Pet}]}, the model does not make Child build on Pet, but the walk did, so a discriminator on a response-only Pet gave Widget the response direction, and requiring a property of Widget was not breaking. Before this PR, a discriminator anywhere made the usage unknown, so it was breaking. With the transform, a reference to a schema with an allOf next to its own $ref, or an alias of one, now makes the usage unknown, because whether the model reads that allOf depends on how the schema is reached. Without the transform, the model never reads it, which the walk already followed. A test covers an allOf next to a $ref reached through a $ref from a child and in an alias, with the transform on and off, and checks whether the usage is known. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 26 ++++++-- .../model/schema_usage_discriminator_test.go | 61 +++++++++++++++++++ 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index 7a35a87d..d5530d65 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -393,8 +393,15 @@ func (w *usageWalker) allOfChildren(parent *yaml.Node) []*yaml.Node { // link records node as a child of the schemas it builds on with allOf, and links those schemas in turn. A schema with a // $ref builds on the schema it refers to as well, so the references are followed too, and an allOf next to a $ref only // counts when the model reads it. A reference that cannot be followed could lead to a parent, so it makes the usage -// unknown. +// unknown. So does a reference to a schema with an allOf next to its own $ref when the model reads that allOf: it +// does where the schema is written, but not when it reaches the schema through a $ref. func (w *usageWalker) link(node *yaml.Node, linked map[*yaml.Node]bool) { + // The sibling transform skips an alias in a list, so whether the model reads an allOf next to the $ref of an aliased + // schema depends on where the alias is. + if w.aliasNextToRef(node, v3.AllOfLabel) { + w.unknown = true + return + } node = utils.NodeAlias(node) if w.unknown || node == nil || linked[node] { return @@ -404,7 +411,7 @@ func (w *usageWalker) link(node *yaml.Node, linked map[*yaml.Node]bool) { switch { case key == v3.RefLabel: target := w.localTarget(utils.NodeAlias(value).Value) - if target == nil { + if target == nil || (w.refSiblings && nextToRef(target, v3.AllOfLabel)) { w.unknown = true return } @@ -419,11 +426,22 @@ func (w *usageWalker) link(node *yaml.Node, linked map[*yaml.Node]bool) { // linkParent records child as a child of parent and links parent in turn. func (w *usageWalker) linkParent(child, parent *yaml.Node, linked map[*yaml.Node]bool) { - parent = utils.NodeAlias(parent) - w.children[parent] = append(w.children[parent], child) + target := utils.NodeAlias(parent) + w.children[target] = append(w.children[target], child) w.link(parent, linked) } +// nextToRef reports whether a schema has keyword next to its $ref. +func nextToRef(node *yaml.Node, keyword string) bool { + return usageField(node, v3.RefLabel) != nil && usageField(node, keyword) != nil +} + +// aliasNextToRef reports whether node is an alias of a schema with keyword next to its $ref, which the model reads +// with TransformSiblingRefs in some places but not in others. +func (w *usageWalker) aliasNextToRef(node *yaml.Node, keyword string) bool { + return w.refSiblings && node != nil && node.Kind == yaml.AliasNode && nextToRef(node.Alias, keyword) +} + // 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) { diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 34608d3b..169bd190 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -366,6 +366,67 @@ func TestRequiredDiscriminatorChildNextToAReference(t *testing.T) { } } +func TestRequiredDiscriminatorKeywordsNextToAReference(t *testing.T) { + // Nothing else refers to Widget, so requiring a property of it is only not breaking when the response can select + // it. The schema model reads the keywords next to a $ref 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. When that depends on how the schema is reached, the usage is unknown. + const pets = ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'}` + const pet = "\n Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" + const other = "\n Other: {type: object}" + for _, tc := range []struct { + name, operation, schemas, paths string + // breaking and known are the results with the transform on and then off. + breaking, known [2]bool + }{ + {"allOf next to a reference, reached through a reference from a child", usageUnused, + pet + other + "\n Child: {allOf: [{$ref: '#/components/schemas/Mid'}, {$ref: '#/components/schemas/Widget'}]}" + + "\n Mid: {$ref: '#/components/schemas/Other', allOf: [{$ref: '#/components/schemas/Pet'}]}", + pets, [2]bool{true, true}, [2]bool{false, true}}, + {"allOf next to a reference in an alias", usageUnused, + pet + other + "\n Mid: &mid {$ref: '#/components/schemas/Other', allOf: [{$ref: '#/components/schemas/Pet'}]}" + + "\n Child: {allOf: [*mid, {$ref: '#/components/schemas/Widget'}]}", + pets, [2]bool{true, true}, [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 { + spec := usageSpec(tc.operation, usageWidget(required)+tc.schemas) + if tc.paths != "" { + spec = strings.Replace(spec, "\ncomponents:", tc.paths+"\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 + } + left := build("name") + assert.Equal(t, tc.known[i], buildSchemaUsage(left.Index) != nil) + changes := CompareDocuments(left, 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 TestSchemaUsageDiscriminatorParentWithUnresolvedReferences(t *testing.T) { // The schema behind a reference that cannot be followed could build on Base, so Base could select Remote. for _, tc := range []struct { From e90d39daca4c76e81aee8b6d85d7508d1672e305 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 17:38:48 +0100 Subject: [PATCH 09/11] fix(what-changed): keep the usage unknown with a discriminator 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 in a document with a discriminator, because the discriminator made the usage unknown. With this PR, following a discriminator could make it matter, for example: - a discriminator next to the $ref of Holder: {$ref: Other, discriminator: ...} reached through a $ref, or in the keywords next to it, - keywords the model drops in a schema that a discriminator selects, - Holder: {$ref: Other, properties: {w: {$ref: Widget}}} in one response and a discriminator in another, - content next to the $ref of a response in a document with a discriminator. 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, including a $ref whose value is an alias while looking for the children of a parent discriminator, and whether it followed a discriminator. When both happen, the usage is unknown, as on main, whatever the order. Documents without such keywords keep the usage of their discriminators. The schemas a discriminator selects are walked as written, as the model reads a component schema, which matches the children found for an Alias with an allOf next to its $ref. Tests cover a discriminator next to a $ref written in place, reached through a $ref, in the keywords next to it and in an alias, a parent discriminator next to a $ref, and keywords next to the $ref of a mapping target and of a child, each with the transform on and off and whether the usage is known. Others cover a discriminator elsewhere in the document, content next to the $ref of a response and of a path item, and a $ref whose value is an alias, each with a document without such keywords that keeps the usage. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 41 +++- .../model/schema_usage_discriminator_test.go | 175 +++++++++++++++++- 2 files changed, 212 insertions(+), 4 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index d5530d65..ba713b84 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -113,6 +113,11 @@ type usageWalker struct { // refSiblings reads the keywords next to $ref, as the schema model does with TransformSiblingRefs. Without it, the // model reads a schema with a $ref as the referenced schema alone. refSiblings 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 discriminated once it follows a discriminator. + throughDropped, discriminated bool // children lists, for each schema, the schemas that build on it directly: with allOf, or with a $ref to it. It is // built for the first discriminator that needs it, and positions is built at the same time. children map[*yaml.Node][]*yaml.Node @@ -149,7 +154,9 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { w.each(value, pathItemObject, sharedSchema) } } - if w.unknown { + // The walk follows the keywords the model drops next to a $ref, as it did before. That did not matter in a document + // with a discriminator, whose usage was unknown, so it stays unknown when both happen. + if w.unknown || (w.discriminated && w.throughDropped) { return nil } return w.visited[schemaObject] @@ -193,10 +200,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 @@ -217,16 +233,27 @@ 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. + dropped := (object != schemaObject || !w.refSiblings || 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) @@ -246,6 +273,9 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect case schemaObject: w.schemaField(node, key, value, dir, sameInstance) } + if dropped { + w.dropped-- + } } } @@ -296,8 +326,10 @@ func (w *usageWalker) schemaField(node *yaml.Node, key string, value *yaml.Node, // discriminator follows the schemas its mapping and default mapping name. Next to a oneOf or an anyOf it can only // select one of the listed schemas, which the walk follows already. Otherwise it is on a parent schema, and can -// select any component schema that builds on the parent with allOf by name. +// select any component schema that builds on the parent with allOf by name. The schemas it selects are walked as +// written, as the model reads a component schema. func (w *usageWalker) discriminator(holder, node *yaml.Node, dir schemaDirection) { + w.discriminated = true for key, value := range usageFields(node) { switch key { case base.MappingLabel: @@ -410,6 +442,9 @@ func (w *usageWalker) link(node *yaml.Node, linked map[*yaml.Node]bool) { for key, value := range usageFields(node) { switch { case key == v3.RefLabel: + if value.Kind == yaml.AliasNode { + w.throughDropped = true + } target := w.localTarget(utils.NodeAlias(value).Value) if target == nil || (w.refSiblings && nextToRef(target, v3.AllOfLabel)) { w.unknown = true diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index 169bd190..f15f2d83 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -370,7 +370,7 @@ func TestRequiredDiscriminatorKeywordsNextToAReference(t *testing.T) { // Nothing else refers to Widget, so requiring a property of it is only not breaking when the response can select // it. The schema model reads the keywords next to a $ref 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. When that depends on how the schema is reached, the usage is unknown. + // drops the rest. A discriminator anywhere in the keywords it drops makes the usage unknown, as before this PR. const pets = ` /pets: get: @@ -382,19 +382,73 @@ func TestRequiredDiscriminatorKeywordsNextToAReference(t *testing.T) { schema: {$ref: '#/components/schemas/Pet'}` const pet = "\n Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" const other = "\n Other: {type: object}" + holder := strings.Replace(usageResponseOnly, "Widget", "Holder", 1) for _, tc := range []struct { name, operation, schemas, paths string // breaking and known are the results with the transform on and then off. breaking, known [2]bool }{ + {"discriminator written next to a reference", + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{$ref: '#/components/schemas/Other', discriminator: {propertyName: kind, mapping: {w: Widget}}}", 1), + other, "", [2]bool{false, true}, [2]bool{true, false}}, + {"discriminator next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', discriminator: {propertyName: kind, mapping: {w: Widget}}}", + "", [2]bool{true, true}, [2]bool{false, false}}, + {"discriminator in the properties next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', properties: {p: {discriminator: {propertyName: kind, mapping: {w: Widget}}}}}", + "", [2]bool{true, true}, [2]bool{false, false}}, + {"discriminator in an allOf written next to a reference", + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{$ref: '#/components/schemas/Other', allOf: [{discriminator: {propertyName: kind, mapping: {w: Widget}}}]}", 1), + other, "", [2]bool{false, true}, [2]bool{true, false}}, + {"parent discriminator next to a reference, reached through a reference", holder, + other + "\n Holder: {$ref: '#/components/schemas/Other', discriminator: {propertyName: kind}}" + + "\n Child: {allOf: [{$ref: '#/components/schemas/Holder'}, {$ref: '#/components/schemas/Widget'}]}", + "", [2]bool{true, true}, [2]bool{false, false}}, {"allOf next to a reference, reached through a reference from a child", usageUnused, pet + other + "\n Child: {allOf: [{$ref: '#/components/schemas/Mid'}, {$ref: '#/components/schemas/Widget'}]}" + "\n Mid: {$ref: '#/components/schemas/Other', allOf: [{$ref: '#/components/schemas/Pet'}]}", pets, [2]bool{true, true}, [2]bool{false, true}}, + // The sibling transform skips an alias in a list, so the model reads it as the target of its $ref there, but + // not in every other place. + {"discriminator next to a reference in an alias", + " x-holder: &holder {$ref: '#/components/schemas/Other', discriminator: {propertyName: kind, mapping: {w: Widget}}}\n" + + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{anyOf: [*holder]}", 1), + other, "", [2]bool{true, true}, [2]bool{false, false}}, + {"discriminator in the properties next to a reference in an alias", + " x-holder: &holder {$ref: '#/components/schemas/Other', properties: {p: {discriminator: {propertyName: kind, mapping: {w: Widget}}}}}\n" + + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{anyOf: [*holder]}", 1), + other, "", [2]bool{true, true}, [2]bool{false, false}}, {"allOf next to a reference in an alias", usageUnused, pet + other + "\n Mid: &mid {$ref: '#/components/schemas/Other', allOf: [{$ref: '#/components/schemas/Pet'}]}" + "\n Child: {allOf: [*mid, {$ref: '#/components/schemas/Widget'}]}", pets, [2]bool{true, true}, [2]bool{false, true}}, + // The schemas a discriminator selects are read as written, as the model reads a component schema, so the + // keywords next to their $ref count with the transform. Keywords the model drops inside them make the usage + // unknown. + {"discriminator next to a reference in a mapping target", + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{type: object, discriminator: {propertyName: kind, mapping: {d: Dog}}}", 1), + other + "\n Dog: {$ref: '#/components/schemas/Other', discriminator: {propertyName: kind, mapping: {w: Widget}}}", + "", [2]bool{false, true}, [2]bool{true, false}}, + {"properties next to a reference in a mapping target", + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{type: object, discriminator: {propertyName: kind, mapping: {d: Dog}}}", 1), + other + "\n Dog: {$ref: '#/components/schemas/Other', properties: {w: {$ref: '#/components/schemas/Widget'}}}", + "", [2]bool{false, true}, [2]bool{true, false}}, + {"properties next to a reference, reached through a reference from a mapping target", + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{type: object, discriminator: {propertyName: kind, mapping: {d: Dog}}}", 1), + other + "\n Dog: {$ref: '#/components/schemas/Holder'}" + + "\n Holder: {$ref: '#/components/schemas/Other', properties: {w: {$ref: '#/components/schemas/Widget'}}}", + "", [2]bool{true, true}, [2]bool{false, false}}, + // Next to an anyOf, the discriminator of the mapping target selects no children, so only its mapping counts. + {"discriminator next to a reference and an anyOf in a mapping target", + strings.Replace(usageResponseOnly, "{$ref: '#/components/schemas/Widget'}", "{type: object, discriminator: {propertyName: kind, mapping: {d: Dog}}}", 1), + other + "\n Dog: {$ref: '#/components/schemas/Other', anyOf: [{type: object}], discriminator: {propertyName: kind, mapping: {w: Widget}}}", + "", [2]bool{false, true}, [2]bool{true, false}}, + {"discriminator next to a reference in a child", usageUnused, + pet + "\n Cat: {$ref: '#/components/schemas/Pet', discriminator: {propertyName: kind, mapping: {w: Widget}}}", + pets, [2]bool{false, true}, [2]bool{true, false}}, + {"properties next to a reference in a child", usageUnused, + pet + "\n Cat: {$ref: '#/components/schemas/Pet', properties: {w: {$ref: '#/components/schemas/Widget'}}}", + pets, [2]bool{false, true}, [2]bool{true, false}}, } { for i, transform := range []bool{true, false} { t.Run(fmt.Sprintf("%s, TransformSiblingRefs %v", tc.name, transform), func(t *testing.T) { @@ -427,6 +481,125 @@ func TestRequiredDiscriminatorKeywordsNextToAReference(t *testing.T) { } } +func TestRequiredDiscriminatorElsewhereWithKeywordsTheModelDrops(t *testing.T) { + // The /widgets response reaches Widget only through the properties next to the $ref of Holder, which the model + // drops, and /bases holds a discriminator. Before this PR the discriminator made the usage unknown, so following + // keywords the model drops did not matter. When both happen, the usage stays unknown. + const bases = ` + /bases: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {type: object, discriminator: {propertyName: kind%s}}` + const other = "\n Other: {type: object}" + holder := strings.Replace(usageResponseOnly, "Widget", "Holder", 1) + for _, tc := range []struct { + name, mapping, schemas string + breaking, known bool + }{ + {"discriminator elsewhere", "", "\n Holder: {$ref: '#/components/schemas/Other', properties: {w: {$ref: '#/components/schemas/Widget'}}}", true, false}, + {"discriminator that also selects the schema", ", mapping: {h: Holder}", "\n Holder: {$ref: '#/components/schemas/Other', properties: {w: {$ref: '#/components/schemas/Widget'}}}", true, false}, + {"no keywords next to a reference", "", "\n Holder: {type: object, properties: {w: {$ref: '#/components/schemas/Widget'}}}", false, true}, + } { + 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(holder, usageWidget(required)+other+tc.schemas) + spec = strings.Replace(spec, "\ncomponents:", fmt.Sprintf(bases, tc.mapping)+"\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 + } + left := build("name") + assert.Equal(t, tc.known, buildSchemaUsage(left.Index) != nil) + changes := CompareDocuments(left, 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 TestRequiredDiscriminatorElsewhereNextToTheReferenceOfAResponseOrPathItem(t *testing.T) { + // The model reads a response or path item with a $ref as the one it refers to, and drops the rest. Only the content + // next to that $ref reaches Widget, and /bases holds a discriminator, so the usage stays unknown, as before. + const content = "content: {application/json: {schema: {$ref: '#/components/schemas/Widget'}}}" + const bases = "\n /bases:\n get:\n responses:\n '200': {description: ok, content: {application/json: {schema: {type: object, discriminator: {propertyName: kind}}}}}" + for _, tc := range []struct { + name, path string + breaking, known bool + }{ + {"response", " get:\n responses:\n '200': {$ref: '#/components/responses/Empty', " + content + "}", true, false}, + {"path item", " $ref: '#/components/pathItems/Empty'\n get:\n responses:\n '200': {description: ok, " + content + "}", true, false}, + {"no reference", " get:\n responses:\n '200': {description: ok, " + content + "}", false, true}, + } { + 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 + bases + + "\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 + } + left := build("name") + assert.Equal(t, tc.known, buildSchemaUsage(left.Index) != nil) + changes := CompareDocuments(left, 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 TestSchemaUsageDiscriminatorWithAReferenceThatIsAnAlias(t *testing.T) { + // The model does not resolve a $ref whose value is an alias, while the walk follows it, as before. With a + // discriminator, the usage is then unknown, as before this PR. + const widgets = "\n /widgets: {get: {responses: {'200': {description: ok, content: {application/json: {schema: {$ref: *widget}}}}}}}" + const bases = "\n /bases: {post: {requestBody: {content: {application/json: {schema: {$ref: '#/components/schemas/Base'}}}}}}" + for _, tc := range []struct { + name, paths, schemas string + known bool + }{ + {"discriminator elsewhere", widgets + bases, "", false}, + {"no discriminator", widgets, "", true}, + {"child that builds on the parent through it", bases, "\n Child: {allOf: [{$ref: *base}]}", false}, + } { + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`x-refs: {widget: &widget '#/components/schemas/Widget', base: &base '#/components/schemas/Base'} +paths:`+tc.paths+` +components: + schemas: + Widget: {type: object} + Base: {type: object, discriminator: {propertyName: kind}}`+tc.schemas), &root)) + idx := index.NewSpecIndexWithConfig(&root, index.CreateClosedAPIIndexConfig()) + assert.Equal(t, tc.known, buildSchemaUsage(idx) != nil, tc.name) + } +} + func TestSchemaUsageDiscriminatorParentWithUnresolvedReferences(t *testing.T) { // The schema behind a reference that cannot be followed could build on Base, so Base could select Remote. for _, tc := range []struct { From a1d23c3d5f18a3474d9b149062679b18e047d9f8 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 21:45:25 +0100 Subject: [PATCH 10/11] fix(what-changed): only accept a boolean discriminator target from OpenAPI 3.1 A mapping or default mapping value that resolves to a boolean was accepted as a boolean schema in every version. Before OpenAPI 3.1 a schema cannot be a boolean, so in a 3.0 document a mapping to '#/paths/~1pets/get/deprecated' kept the usage, and a required entry added to a schema that only a response uses was not breaking. On main, the discriminator makes the usage unknown, so it is breaking. A boolean target is now only a schema when ResolveDocumentVersion confirms OpenAPI 3.1 or later. Otherwise it makes the usage unknown, like any other target that is not a schema. Tests cover a mapping in 3.0 that keeps the usage, and a mapping in 3.0 to a boolean component and to a boolean field, next to the 3.1 and 3.2 cases. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 17 +++++++++++------ .../model/schema_usage_discriminator_test.go | 7 ++++++- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index ba713b84..ddbe4e2c 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -113,6 +113,8 @@ type usageWalker struct { // refSiblings reads the keywords next to $ref, as the schema model does with TransformSiblingRefs. Without it, the // model reads a schema with a $ref as the referenced schema alone. refSiblings bool + // booleanSchemas is set from OpenAPI 3.1, where a schema can be a boolean. + booleanSchemas 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 @@ -133,11 +135,13 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { if root.Kind == yaml.DocumentNode && len(root.Content) > 0 { root = root.Content[0] } + version, versionKnown := idx.ResolveDocumentVersion() w := usageWalker{ - index: idx, - targets: make(map[string]*yaml.Node), - schemas: usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel), - refSiblings: idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, + index: idx, + targets: make(map[string]*yaml.Node), + schemas: usageField(usageField(root, v3.ComponentsLabel), v3.SchemasLabel), + refSiblings: idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs, + booleanSchemas: versionKnown && version >= 3.1, } for i := range w.visited { w.visited[i] = make(schemaUsage) @@ -372,8 +376,9 @@ func (w *usageWalker) discriminatorTarget(value *yaml.Node, dir schemaDirection) ref = "#/components/schemas/" + ref } schema := w.localTarget(ref) - // A pointer can lead to a value that cannot be a schema, such as a string. A boolean schema has nothing to walk. - if schema == nil || (utils.NodeAlias(schema).Kind != yaml.MappingNode && !utils.IsNodeBoolValue(schema)) { + // A pointer can lead to a value that cannot be a schema, such as a string. A boolean schema, from OpenAPI 3.1, has + // nothing to walk. + if schema == nil || (utils.NodeAlias(schema).Kind != yaml.MappingNode && !(w.booleanSchemas && utils.IsNodeBoolValue(schema))) { w.unknown = true return } diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index f15f2d83..dda59794 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -122,12 +122,13 @@ components: func TestRequiredDiscriminatorTargetThatIsNotASchema(t *testing.T) { // Dog is only reachable through the discriminator that a response uses. A pointer to a value that cannot be a - // schema cannot be followed, so the usage is unknown. A boolean schema can be a target. + // schema cannot be followed, so the usage is unknown. From OpenAPI 3.1, a boolean schema can be a target. const spec = `openapi: VERSION info: {title: Direction, version: 1.0.0} paths: /pets: get: + deprecated: false responses: '200': description: ok @@ -149,6 +150,10 @@ components: {"default mapping to a string", "3.2.0", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: '#/info/title'}", true}, {"mapping to a boolean schema", "3.1.0", "{propertyName: kind, mapping: {dog: Dog, any: Anything}}", false}, {"default mapping to a boolean schema", "3.2.0", "{propertyName: kind, mapping: {dog: Dog}, defaultMapping: '#/components/schemas/Anything'}", false}, + // Before OpenAPI 3.1, a schema cannot be a boolean. + {"mapping in OpenAPI 3.0", "3.0.4", "{propertyName: kind, mapping: {dog: Dog}}", false}, + {"mapping to a boolean in OpenAPI 3.0", "3.0.4", "{propertyName: kind, mapping: {dog: Dog, any: Anything}}", true}, + {"mapping to a boolean field in OpenAPI 3.0", "3.0.4", "{propertyName: kind, mapping: {dog: Dog, off: '#/paths/~1pets/get/deprecated'}}", true}, } { t.Run(tc.name, func(t *testing.T) { old := strings.NewReplacer("VERSION", tc.version, "DISCRIMINATOR", tc.discriminator).Replace(spec) From a34cd89754524a702b9d32430dc427d07510f1c6 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Fri, 27 Nov 2026 21:45:25 +0100 Subject: [PATCH 11/11] fix(what-changed): do not select a child by a name that the mapping sends elsewhere A discriminator on a parent can select a component schema that builds on the parent with allOf by its name. When the mapping has that name as a key, the value selects the schema it maps to instead. The walk still gave the child the direction of the discriminator. With Cat and Widget building on a response-only Pet and mapping: {Widget: Cat}, nothing can select Widget, yet a required entry added to it was not breaking. On main, the discriminator makes the usage unknown, so it is breaking. A child is now only selected by name when one of its component names is not a key of the mapping. A mapping value that names the child, such as legacy: Widget, still selects it. The parent is walked as before. Tests cover a name sent to another schema, with and without another value naming the child, a name sent to the child itself, another name sent to another schema, a child listed under two names, and a mapping that sends the name of the parent elsewhere. Co-Authored-By: Claude --- what-changed/model/schema_usage.go | 34 +++++++-- .../model/schema_usage_discriminator_test.go | 71 +++++++++++++++++++ 2 files changed, 99 insertions(+), 6 deletions(-) diff --git a/what-changed/model/schema_usage.go b/what-changed/model/schema_usage.go index ddbe4e2c..4cfe3d53 100644 --- a/what-changed/model/schema_usage.go +++ b/what-changed/model/schema_usage.go @@ -121,10 +121,12 @@ type usageWalker struct { // a $ref the model does not resolve, and discriminated once it follows a discriminator. throughDropped, discriminated bool // children lists, for each schema, the schemas that build on it directly: with allOf, or with a $ref to it. It is - // built for the first discriminator that needs it, and positions is built at the same time. + // built for the first discriminator that needs it, and positions and names are built at the same time. children map[*yaml.Node][]*yaml.Node // positions holds the place of each component schema, so the children are returned in the order they are declared. positions map[*yaml.Node]int + // names holds the names of each component schema, by which a discriminator on a parent can select it. + names map[*yaml.Node][]string } func buildSchemaUsage(idx *index.SpecIndex) schemaUsage { @@ -330,14 +332,19 @@ func (w *usageWalker) schemaField(node *yaml.Node, key string, value *yaml.Node, // discriminator follows the schemas its mapping and default mapping name. Next to a oneOf or an anyOf it can only // select one of the listed schemas, which the walk follows already. Otherwise it is on a parent schema, and can -// select any component schema that builds on the parent with allOf by name. The schemas it selects are walked as -// written, as the model reads a component schema. +// select any component schema that builds on the parent with allOf by name, unless the mapping sends that name to +// another schema. The schemas it selects are walked as written, as the model reads a component schema. func (w *usageWalker) discriminator(holder, node *yaml.Node, dir schemaDirection) { w.discriminated = true + var mapped map[string]bool for key, value := range usageFields(node) { switch key { case base.MappingLabel: - for _, target := range usageFields(value) { + for name, target := range usageFields(value) { + if mapped == nil { + mapped = make(map[string]bool) + } + mapped[name] = true w.discriminatorTarget(target, dir) } case base.DefaultMappingLabel: @@ -353,10 +360,23 @@ func (w *usageWalker) discriminator(holder, node *yaml.Node, dir schemaDirection } } for _, child := range w.allOfChildren(holder) { - w.walk(child, schemaObject, dir) + if child == holder || w.selectedByName(child, mapped) { + w.walk(child, schemaObject, dir) + } } } +// selectedByName reports whether a discriminator can select a component schema by one of its names, which it cannot +// once its mapping sends that name to a schema. When that schema is this one, the mapping follows it already. +func (w *usageWalker) selectedByName(schema *yaml.Node, mapped map[string]bool) bool { + for _, name := range w.names[schema] { + if !mapped[name] { + return true + } + } + return false +} + // componentName is the pattern of a component name, so a mapping value that does not match it is a relative URI. var componentName = regexp.MustCompile(`^[a-zA-Z0-9.\-_]+$`) @@ -391,12 +411,14 @@ func (w *usageWalker) allOfChildren(parent *yaml.Node) []*yaml.Node { if w.children == nil { w.children = make(map[*yaml.Node][]*yaml.Node) w.positions = make(map[*yaml.Node]int) + w.names = make(map[*yaml.Node][]string) linked := make(map[*yaml.Node]bool) - for _, schema := range usageFields(w.schemas) { + for name, schema := range usageFields(w.schemas) { schema = utils.NodeAlias(schema) if _, seen := w.positions[schema]; !seen { w.positions[schema] = len(w.positions) } + w.names[schema] = append(w.names[schema], name) w.link(schema, linked) } } diff --git a/what-changed/model/schema_usage_discriminator_test.go b/what-changed/model/schema_usage_discriminator_test.go index dda59794..a2dd5468 100644 --- a/what-changed/model/schema_usage_discriminator_test.go +++ b/what-changed/model/schema_usage_discriminator_test.go @@ -330,6 +330,77 @@ func TestRequiredDiscriminatorChildOfAResponseParent(t *testing.T) { requireEntryBreaking(t, build("name"), build("name, id"), false) } +func TestRequiredDiscriminatorMappingOverridesAChildName(t *testing.T) { + // Nothing refers to Widget, and Widget and Cat build on Pet, which only a response uses. When the mapping sends the + // value Widget to Cat, the discriminator cannot select Widget by name, so Widget stays unused unless another mapping + // value or another name of Widget selects it. + const pets = ` + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'}` + for _, tc := range []struct { + name, mapping string + gizmo bool + breaking bool + }{ + {"name sent to another schema", "{Widget: '#/components/schemas/Cat'}", false, true}, + {"name sent to another schema and another value naming widget", "{Widget: '#/components/schemas/Cat', legacy: Widget}", false, false}, + {"name sent to widget", "{Widget: Widget}", false, false}, + {"other name sent to another schema", "{Gadget: Cat}", false, false}, + // Gizmo is an alias of Widget, so Widget is listed under two names. + {"one of two names sent to another schema", "{Widget: Cat}", true, false}, + {"other of two names sent to another schema", "{Gizmo: Cat}", true, false}, + {"both names sent to another schema", "{Widget: Cat, Gizmo: Cat}", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + schemas := ` + Pet: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind, mapping: ` + tc.mapping + `}} + Cat: {allOf: [{$ref: '#/components/schemas/Pet'}]}` + build := func(required string) string { + widget := usageChild(required, "allOf: [{$ref: '#/components/schemas/Pet'}]") + if tc.gizmo { + widget = strings.Replace(widget, " Widget:\n", " Widget: &widget\n", 1) + "\n Gizmo: *widget" + } + spec := usageSpec(usageUnused, widget+schemas) + return strings.Replace(spec, "\ncomponents:", pets+"\ncomponents:", 1) + } + requireEntryBreaking(t, build("name"), build("name, id"), tc.breaking) + }) + } +} + +func TestRequiredDiscriminatorMappingOverridesTheParentName(t *testing.T) { + // Only a response uses Pet, which holds the discriminator, but a field declared by one of its subschemas can bypass + // its unevaluatedProperties rule, so the walk gives Pet itself both directions. The mapping sending the value Pet to + // Dog does not change that, because the discriminator is on Pet. + const spec = `openapi: 3.1.0 +info: {title: Direction, version: 1.0.0} +paths: + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '#/components/schemas/Pet'} +components: + schemas: + Pet: + type: object + unevaluatedProperties: false + required: [kind] + properties: {kind: {type: string}, name: {type: string}} + discriminator: {propertyName: kind, mapping: {Pet: Dog}} + Dog: {type: object}` + requireEntryBreaking(t, spec, strings.Replace(spec, "required: [kind]", "required: [kind, name]", 1), true) +} + func TestRequiredDiscriminatorChildNextToAReference(t *testing.T) { // Nothing refers to Widget, and Alias refers to it next to an allOf with Pet, which only a response uses. With // TransformSiblingRefs the schema model reads Alias as both, so only that response can select it. Without it, the