Skip to content

Polymorphic subtypes discovery - #65

Merged
fredbi merged 2 commits into
go-openapi:masterfrom
fredbi:polymorphic-subtypes-discovery
Jul 30, 2026
Merged

fredbi merged 2 commits into
go-openapi:masterfrom
fredbi:polymorphic-subtypes-discovery

Conversation

@fredbi

@fredbi fredbi commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Change type

Please select: 🆕 New feature or enhancement|🔧 Bug fix'|📃 Documentation update

Short description

Fixes

Full description

Checklist

  • I have signed all my commits with my name and email (see DCO. This does not require a PGP-signed commit
  • I have rebased and squashed my work, so only one commit remains
  • I have added tests to cover my changes.
  • I have properly enriched go doc comments in code.
  • I have properly documented any breaking change.

fredbi and others added 2 commits July 30, 2026 14:32
A polymorphic family was emitted incompletely: the reference direction runs
subtype -> base ($ref to the base), never base -> subtype, so a route that
references a discriminated base reached the base and stopped. The subtypes came
out only under ScanModels (-m), which emits every annotated model whether it
belongs to the family or not — and under -m + PruneUnusedModels they were built
and then pruned away, since no $ref reaches them. Either way a consumer got a
definition carrying `discriminator` with nothing to discriminate between.

Add the reverse `swagger:allOf` index (internal/builders/spec/subtypes.go):
base Go type identity -> the swagger:model declarations that declare that base
as an allOf member. It is fed by the model index, which classification
populates whether or not ScanModels is set — that independence is what makes
the pull possible with no -m. Keyed by Go type identity (<pkgpath>.<Name>)
rather than swagger name, the one fact both ends can compute without knowing
the other's `swagger:model` override; entries are ordered by definition key so
the pull order does not follow map iteration. A relation is an embedded member
carrying `swagger:allOf` — a struct's anonymous field or an interface's
anonymous interface. Pointers are unwrapped, an alias is indexed under both its
own and the aliased type's identity, `swagger:ignore` drops the embed exactly
as the schema builder does, and a plain (unannotated) embed is not a subtype.
DefaultAllOfForEmbeds is deliberately not honoured: it is a rendering knob, and
letting it decide which definitions exist would be a surprising coupling.

Two hooks consume the index:

- discovery (buildDiscoveredSchema): a definition that has just been built and
  declares a discriminator appends its subtypes to s.discovered, so the
  existing fixpoint loop builds them and keeps discovering their own
  dependencies. Each genuinely new pull raises a located
  scan.discovered-subtype Hint. A no-op under ScanModels, where every model is
  built up front anyway — pulling there would add nothing and would emit Hints
  in model-index map-iteration order.
- prune reachability: a reachable discriminated base marks its subtypes
  reachable, so a family is kept or dropped as a unit. This is the
  discriminator rule #2639's prune deferred to this feature.

The gate is the built definition's own discriminator (isDiscriminated), not a
source-level re-derivation: it reads identically for an interface base with a
`discriminator: true` member and a struct base with a `discriminator: true`
property. It also matches a MID-LEVEL base — a subtype that is itself a base
renders as allOf: [{$ref parent}, {own props, discriminator}], so its
discriminator sits in its compound member, not at the top level. The $ref
member is deliberately not followed, so a leaf never inherits its base's
discriminator and never pulls in its own siblings. Multi-level hierarchies
cascade for free through the discovery fixpoint: the root pulls the mid-level
type, which then pulls the leaves on the next round.

Reachability, not existence: the trigger is a base ENTERING the document, so a
discriminated base nothing references pulls nothing (and under prune is dropped
together with its subtypes). Bases are not made roots — that would reintroduce
the over-generation this fixes, narrowed to discriminated types.

Always on, with no new Option: a definition carrying `discriminator` whose
subtypes are absent is an unusable polymorphic family, so this is a fix rather
than a preference. Default output changes for discriminated bases only; no
existing golden in the corpus drifts.

Two fixtures, each witnessed in all three modes (no -m / -m / -m + prune):
enhancements/discriminated-subtypes (cross-package subtypes, transitive
discovery from a pulled subtype, negative controls for over-pull and for the
discriminated gate, plus edges/ for pointer, alias, ignored and plain embeds in
a family no route references) and enhancements/discriminated-subtypes-nested
(Shape -> Polygon -> Square/Triangle, a two-level hierarchy).

Contributes to go-swagger/go-swagger#1913.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
The "Polymorphic models" tutorial told readers the opposite of what codescan
now does: "a subtype appears only when something references it or you scan with
ScanModels — codescan does not auto-discover subtypes from the base alone."

Replace that paragraph with two sections, both backed by test-covered witnesses
so the prose cannot drift from real scanner output:

- "How subtypes are discovered" — why the reference direction makes a family
  awkward (a subtype $refs its base, nothing $refs a subtype, so returning the
  base reaches the base and stops), that codescan therefore looks the relation
  up backwards, and the three consequences: reachability-not-existence (a base
  nothing references still emits nothing — bases are not roots), the family
  travelling as a unit through PruneUnusedModels, and only swagger:allOf
  counting (DefaultAllOfForEmbeds changes rendering, not which definitions
  exist). Shows the whole no-ScanModels spec next to the route that references
  only the base, plus the scan.discovered-subtype Hint stream verbatim.
- "Multi-level hierarchies" — a subtype that is itself a base, written as an
  interface so the concrete structs beneath it can embed it, with a table of
  where each level's discriminator lands: top level for the root, inside its own
  allOf member for an intermediate type, none for a leaf.

Witnesses: docs/examples/concepts/polymorphism gains a route returning the base
(so discovery is observable) and two goldens — the whole reachable-only spec and
the Hint stream; new docs/examples/concepts/polymorphism-nested covers the
two-level hierarchy and locks each level's discriminator placement. Both follow
the established witness conventions: the swagger:route lives in a bare comment
block and the response type is exported, so neither trips the `unused` linter.
Test helpers in the polymorphism witness are factored onto a shared
assertGolden.

Two consistency edits elsewhere in the site: the "When the scanner emits a type"
rule gains its third case (subtype of an emitted discriminated base — the one
case where a definition arrives with nothing referencing it), and the prune
page's reachability walk documents the one rule that does not follow a $ref.
ROADMAP marks v0.37's "Discriminator / polymorphism discovery" done.

Also run `go mod tidy` in docs/examples: the module replaces the root module, so
the recent dependency bumps left its go.mod/go.sum stale and every witness test
failed with "updates to go.mod needed" before this.

Verified with a full `hugo` build (105 pages, no warnings): the new shortcodes
resolve their files, both new sections render, and every relref — inbound and
outbound, including the #how-subtypes-are-discovered anchors — points at a real
page.

Contributes to go-swagger/go-swagger#1913.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
@codecov

codecov Bot commented Jul 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.76068% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.73%. Comparing base (0c2878c) to head (3bd0c93).
⚠️ Report is 3 commits behind head on master.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
internal/builders/spec/subtypes.go 82.88% 11 Missing and 8 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #65      +/-   ##
==========================================
+ Coverage   81.63%   81.73%   +0.09%     
==========================================
  Files          84       85       +1     
  Lines        8528     8645     +117     
==========================================
+ Hits         6962     7066     +104     
- Misses       1146     1153       +7     
- Partials      420      426       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@fredbi
fredbi merged commit 7b27a5e into go-openapi:master Jul 30, 2026
25 of 26 checks passed
@fredbi
fredbi deleted the polymorphic-subtypes-discovery branch July 30, 2026 13:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

⌂ 换网址