Skip to content

Validate the constraints block of Bean Validation annotated domain classes and expose their constraints - #16624

Open
jdaugherty wants to merge 15 commits into
apache:9.0.xfrom
jdaugherty:fix/gorm-bean-validation-constraints
Open

jdaugherty wants to merge 15 commits into
apache:9.0.xfrom
jdaugherty:fix/gorm-bean-validation-constraints

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

A domain class carrying a jakarta.validation annotation is validated by Hibernate Validator through GormValidatorAdapter, which until now replaced GORM's own validator entirely: the constraints block was ignored for validation while it still defined the schema, the validator exposed no constraint metadata (it was not a PersistentEntityValidator, so constrainedProperties was empty for scaffolding and plugins, and validation cascading into such a class checked nothing), null values were never reached by @NotNull and friends because the traversable resolver treated a null property as uninitialized, and the unit test datastore ignored the annotations altogether.

JakartaValidatorRegistry now registers a JakartaPersistentEntityValidator for an annotated entity: a PersistentEntityValidator that validates the constraints block, cascades to the associations like any other, and then validates the annotations with Bean Validation, which cascades only where GORM has nothing to cascade to: through a @Valid property that is not an association between entities, such as a transient property or a basic collection. PersistentEntityValidator gains the validateBeyondConstraints hook the subclass implements, called for the root object and for each associated object under the path of its association, and validates an associated entity with the constraints its validator validates rather than the ones it exposes. An associated instance of a subclass that is an entity of its own is validated with the rules and the validator of that entity, whatever the declared type of the association, as validate() hands such an instance to the validator of its own entity. The beforeValidate callback of an associated instance runs before its constraints are chosen, so rules that depend on its state, such as the sequence of a @GroupSequenceProvider, are the ones of the state the callback leaves. Validation hints travel down the cascade: the validator of the entity owning an association gives the hints of the associated object (getAssociationValidationHints), and the validator of the associated entity validates it with them. An object associated through a property marked @Valid is thus validated in the groups of its owner, converted as @ConvertGroup declares, as Bean Validation cascades, and any other associated object in the default group, as on its own. A conversion applies to the groups the provider validates when a group of the owner is validated: a group sequence an earlier conversion targets is expanded, in its order, before the conversions of a nested association apply, and a group brings the groups it extends; a sequence none of whose groups is converted is passed on as it is, so it still stops at its first group with a violation. A group is validated once: a group given both on its own and in a sequence is skipped by the sequence, as Bean Validation reports each violation once, and a violation of the constraints block counts as one of the first group the object is validated in, so it stops a sequence as that group does. An associated object reached through two associations is validated once with each list of groups. PersistentEntityValidator is a SmartValidator, as the adapter it replaces was: the validation hints Spring's DataBinder and ValidationUtils pass are the groups an annotated entity is validated in, and it cascades with them. The GORM nullable constraint is relaxed for a property whose nullability an annotation of the validated groups declares, so a null value is reported once; an annotation of another group leaves the block in force.

The exposed constraints merge the block with a description of the annotations (JakartaConstraintsTranslator), read from the Bean Validation descriptors of the class and of its superclasses, so that a composed constraint carries its attribute overrides. Only the default group is described: as Hibernate Validator applies it, the first class from the class up to redefine the default group with a @GroupSequence applies the sequence to its own constraints and to the ones of its superclasses, while the classes below it validate theirs in the Default group. A decimal bound of an integer property is described as the nearest whole number it admits, and a getter without a backing field is left out. Every consumer that looks for a PersistentEntityValidator, such as the fields plugin, the GraphQL properties and the OpenAPI descriptions, sees the merged constraints without a change.

MappingContextTraversableResolver treats a null value as reachable. DataTest creates the same validator for annotated domain classes. The Hibernate 5 and 7 specs are replaced by one TCK spec that runs on every datastore. The grails-hibernate test apps of Hibernate 5 and Hibernate 7 cover a domain class constrained with annotations only, end to end: save(), failOnError, an update, the cascade, constrainedProperties, message resolution, and a form posted to a controller.

Documented in a new Bean Validation Annotations section of the validation guide and in the Grails 9 upgrade notes.

Verification

Validated at cbcea53ef1b0, whose tree is fc1b021c3e5af566d8c77756808b79b17b2c531e:

  • Final aggregate: 34,246 cases, zero failures, zero errors and 490 skipped.
  • The DataTest constraint-validator service-injection regression and all four existing EL-bounds regressions pass. The EL fix is upstream Align standalone EL with Hibernate Validator 9 #17175 in the merged base, not an EL implementation change in this PR.
  • BeanValidationSpec: 27 TCK cases each on Hibernate 5, Hibernate 7, MongoDB and Neo4j, for 108 passed and zero skipped. The 27 simple-datastore cases retain their existing exclusion.
  • Root style checks, enabled PMD, RAT, dependency/BOM validation and buildHealth passed.
  • Guide task: FROM-CACHE. The merge preserves the EL and Bean Validation upgrade-note sections; guide outputs were not rebuilt in this validation.

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 47.0212%. Comparing base (d801680) to head (af5d40a).
⚠️ Report is 44 commits behind head on 9.0.x.

Additional details and impacted files

Impacted file tree graph

@@               Coverage Diff                @@
##             9.0.x     #16624         +/-   ##
================================================
+ Coverage         0   47.0212%   +47.0212%     
- Complexity       0        913        +913     
================================================
  Files            0         94         +94     
  Lines            0       5153       +5153     
  Branches         0        901        +901     
================================================
+ Hits             0       2423       +2423     
- Misses           0       2399       +2399     
- Partials         0        331        +331     

see 94 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jdaugherty
jdaugherty force-pushed the fix/gorm-bean-validation-constraints branch from 2894f42 to 2803750 Compare October 20, 2026 14:59

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of #16624 at 280375075f (base 8.0.x). It is one commit on bd0c1394ce9, 10 commits behind the current 8.0.x tip d1f7b1ee0a, and git merge-tree against the tip is clean.

What I ran and checked:

  • Tests at the head, all green:
    • :grails-datamapping-core:test: 1799 tests.
    • :grails-testing-support-datamapping:test.
    • grails.gorm.tests.validation.* on Hibernate 5 and Hibernate 7.
  • Style: CodeNarc and Checkstyle on the changed main sources are clean.
  • Probe specs, not committed, run at the head and on 8.0.x: with DataTest and with a real Hibernate 5 HibernateDatastore. They cover cascading into associations, a group-restricted annotation, a cross-field @AssertTrue, a class-level constraint, and a null @NotBlank saved with flush: true.
  • CI: the red jobs are MongoDB container start failures in the Groovy snapshot canary shards and in one MongoDB functional job. They aren't related to this change.

Fixing the traversable resolver for null values and validating annotated domain classes in DataTest are clear bug fixes. Merging the constraints block with the annotations is the right model. Before merge, I'd like 1 and 2 fixed, or the guide changed to match, and 4 corrected.

1. Cascading into an annotated domain class checks none of its constraints

The probe gives the same result with DataTest and with Hibernate 5:

@Entity
class Parent {
    @NotNull String name
    static hasMany = [children: Child]
}

@Entity
class Child {
    @NotBlank String label
    String code
    static belongsTo = [parent: Parent]
    static constraints = { code nullable: false }
}

def parent = new Parent(name: 'p')
parent.addToChildren(new Child(label: '', code: null))
parent.validate()   // true: neither @NotBlank nor nullable: false of the child is checked

PersistentEntityValidator.cascadeValidationToOne (grails-datamapping-validation/src/main/groovy/grails/gorm/validation/PersistentEntityValidator.groovy:242-248) takes the associated entity's constraints only when that entity's validator is a PersistentEntityValidator. For a GormValidatorAdapter it uses an empty map. On top of that, this change turns off Bean Validation cascading whenever the GORM validator runs (GormValidatorAdapter.groovy:91).

The probe covered three combinations:

  • A plain parent with an annotated child: the child isn't checked either.
  • An annotated parent with a plain child: the child is checked.
  • On 8.0.x: the annotated child isn't checked either, even with @Valid Set<Child> children. So this isn't a regression.

The new guide says the opposite, though (beanValidation.adoc:49):

GORM cascades validation to the associations of an annotated domain class exactly as it does for any other domain class, so @Valid is not needed on an association between domain classes and has no additional effect there.

That holds only when the associated class has no annotations. An application that uses annotations will usually use them on both sides.

The adapter now carries the entity's PersistentEntityValidator, so cascadeValidationToOne could do two things when it meets a GormValidatorAdapter:

  • take the GORM constraints from the adapter's entityValidator;
  • run the adapter's Bean Validation validator on the associated object under the nested path. SpringValidatorAdapter already prefixes field errors with the nested path of the Errors.

If that is out of scope here, please narrow the guide sentence instead, and add a spec that pins down the current behaviour.

2. A group-restricted annotation removes nullable: false from the block

interface OnCreate {}

@Entity
class GroupBean {
    @NotNull(groups = OnCreate) String name
    static constraints = { name nullable: false }
}

new GroupBean().validate()   // true
// and constrainedProperties.name.nullable == false

findNullabilityConstrainedProperties (JakartaConstraintsTranslator.groovy:120) counts the annotation whatever its groups are, so delegateNullabilityToBeanValidation relaxes the block's nullable: false. But validate() runs Bean Validation for the Default group only.

The result:

  • Nothing checks for null.
  • The exposed metadata still says the property is required.
  • The column stays NOT NULL, so the insert fails at flush.

I'd only count an annotation whose groups() is empty or contains jakarta.validation.groups.Default, both in the nullability delegation and in translate. The guide sentence at beanValidation.adoc:47 could then say "annotations of the default group".

3. 8.0.x or 9.0

You asked about this in the description. I'm fine with 8.0.x, because most of the change turns a failure at flush into a validation error:

  • On 8.0.x, a null @NotBlank property passes validate(). Hibernate's own persist-time Bean Validation then throws jakarta.validation.ConstraintViolationException (save(flush: true) on Hibernate 5).
  • nullable, unique and maxSize in the block already shape the schema.

Rules that never reach the schema are different. On 8.0.1 they start rejecting data that 8.0.0 saved:

  • validator:
  • matches
  • inList
  • min and max
  • email
  • the global grails.gorm.default.constraints

The upgrade note (upgrading80x.adoc:4821) could name them, the global default constraints in particular. An application won't necessarily connect those with its annotated classes.

4. "Class level constraints are now validated"

Class-level constraints were already validated before this change. Hibernate Validator doesn't consult the TraversableResolver for a class-level constraint (ValidatorImpl.needToCallTraversableResolver).

The probe used an entity with @NotNull String name and a custom class-level @OrderedRange constraint. On 8.0.x and at the head alike, validate() returns false with an OrderedRange error.

So this needs two fixes:

  • Drop the bullet in the upgrade note (upgrading80x.adoc:4826).
  • Correct the sentence in the commit message and the description.

The propertyName == null branch in MappingContextTraversableResolver.isReachable can stay as a guard, but its comment suggests Hibernate Validator calls it for class-level constraints, and it never does.

5. Smaller points

  • Broken link: link:{constraintsRef}[constraint] (beanValidation.adoc:45) resolves to ../ref/Constraints/, which has no index page. Linking the Constraints section of the validation guide would work.
  • Test placement: the Hibernate 5 and Hibernate 7 BeanValidationSpec additions are nearly the same. MongoDB gets the same JakartaValidatorRegistry through ValidatorRegistries but has no test. One TCK spec in grails-datamapping-tck would cover every datastore. It would also be a natural place for regression tests of 1 and 2.
  • Cross-field getters: a cross-field @AssertTrue boolean isRangeValid() appears in constrainedProperties as a property rangeValid with inList: [true]. As far as I can see this is harmless for the fields plugin and OpenAPI, which skip names that aren't properties. Still, leaving out getters without a backing property would keep the metadata to real properties.
  • OpenAPI output changes: GrailsModelConverter.entityConstraints in grails-openapi now gets constraints for annotated domain classes, where it used to get an empty map. The generated schema for those classes changes (required lists, nullable references). That's probably what we want, but it has no test, and the upgrade note could mention it next to scaffolding and the fields plugin.

Verified as correct

  • The null fix:
    • On Hibernate 5 and 7, HibernateProxyHandler.isInitialized(null) returns false, which is why @NotNull never fired there. GroovyProxyFactory and JavassistProxyFactory already treated null as initialised.
    • The new isReachable reads the value through ClassPropertyFetcher, as the handlers' isInitialized(obj, name) did. So an uninitialised proxy or a lazy collection is still unreachable.
  • Nullability delegation:
    • It changes only the validator's own constraints, which come from a fresh evaluate().
    • The Hibernate binder reads PropertyConfig, so the schema is unchanged.
    • With @NotNull and nullable: false on the same property, a null is reported once, as NotNull.
  • Unannotated properties: with the Grails 8 default nullable: true, they stay optional, so validating the block doesn't suddenly make them required.
  • unique survives the copy into the exposed constraints:
    • Hibernate 5, Hibernate 7 and MongoDB add UniqueConstraint to the registry that createEntityValidator builds with.
    • DataTest adds it to the constraintRegistry bean it passes in.
  • DataTest wiring: grails-datamapping-core has hibernate-validator as an implementation dependency, so Jakarta Validation is on the runtime classpath. The new checks in DataTest and DataTestSetupSpecInterceptor can't hit a missing class. The new testImplementation is only for compiling the test entity.
  • Caching: the mapping context already caches the validator per entity, and the registry's own cache is a ConcurrentHashMap.
  • Docs: the toc.yml entry, the validation.html#beanValidation and testing.html#unitTestingDomainClasses anchors, and the upgrade-note number (87, after 86).

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not approving. An unannotated domain class still uses PersistentEntityValidator, and root-level Grails constraints are applied. Three production gaps remain.

Disabling Bean Validation cascading does not hand the associated entity to a validator that will run. PersistentEntityValidator.cascadeValidationToOne() only reads constraints from a PersistentEntityValidator. An associated GormValidatorAdapter contributes nothing, so an annotated parent with @Valid to an annotated child can pass while the child is invalid. That cascading used to be rejected.

A grouped @NotNull also relaxes the Grails nullable: false constraint even when ordinary validate() does not run that group, so both validators accept null.

grails-fields DomainPropertyImpl still requires validator instanceof PersistentEntityValidator (line 57). The new adapter fails that check, so the fields plugin still does not see the constraints this pull request says it exposes. That file is not in this diff.

@jdaugherty
jdaugherty force-pushed the fix/gorm-bean-validation-constraints branch from 2803750 to d4f19e4 Compare October 21, 2026 20:16
@jdaugherty

Copy link
Copy Markdown
Contributor Author

@matrei

Thanks for the thorough probe. All of 1, 2, 4 and the smaller points are addressed in the amended commit; the approach changed in one respect that also answers @jamesfredley's fields plugin point.

Design change. The validator JakartaValidatorRegistry registers for an annotated entity is now JakartaPersistentEntityValidator, a PersistentEntityValidator subclass, rather than a GormValidatorAdapter carrying one. It validates the constraints block and cascades as the base class does, then runs Bean Validation (without cascading) through a new protected hook, PersistentEntityValidator.validateBeyondConstraints(obj, errors), which the base class calls for the root object and, in cascadeValidationToOne, for each associated object under the nested path of its association. So every consumer that does validator instanceof PersistentEntityValidator (the cascade itself, DomainPropertyImpl in grails-fields, PersistentGraphQLProperty, and any plugin outside this repo) sees the merged constraints without a change. GormValidatorAdapter is back to its 8.0.0 shape.

  1. Cascading. cascadeValidationToOne now validates an annotated associated entity with the constraints its validator validates (a new protected getValidatedConstrainedProperties(), the evaluated block with the nullability relaxed) rather than the merged ones it exposes, so the translated metadata is not checked a second time, and then calls the hook, so the annotations of the child are checked under lines[0].label. One cycle guard (validatedObjects), Bean Validation never cascades. Covered for an annotated parent, a plain parent, a single execution and deepValidate: false in the new TCK spec, the DataTest spec and JakartaValidatorRegistrySpec.
  2. Groups. JakartaConstraintsTranslator now reads the BeanDescriptor of the class and keeps only the constraints whose groups intersect the default group of the class (Default, plus the groups of a @GroupSequence redefining it), both for the nullability delegation and for the description. A @NotNull(groups = OnPublish) leaves nullable: false of the block in force: validate() and save() reject the null with nullable, and the metadata still says required. The guide says "annotations of the default group" now.
  3. 8.0.x. The upgrade note now separates the rules that already shaped the schema (nullable, unique, maxSize, a failure moves from flush to validate()) from the ones enforced for the first time (validator, matches, inList, min/max, email, blank, and the global grails.gorm.default.constraints), and asks to review the block and the global defaults of each annotated class.
  4. Class level constraints. Bullet dropped, the commit message and the description corrected, and the propertyName == null branch of the resolver kept as a guard with a comment saying Hibernate Validator does not consult it for a class level constraint (the spec test is renamed accordingly). The TCK spec pins the behaviour with a class level constraint.
  5. Smaller points:
    • the link is link:validation.html#constraints[constraint] now;
    • the Hibernate 5 and 7 additions are replaced by org.apache.grails.data.testing.tck.tests.BeanValidationSpec (six domains under tck/domains), which runs on Hibernate 5, Hibernate 7, MongoDB and Neo4j and is ignored on the simple datastore of the core suite, which registers no validator;
    • a getter without a backing field (isRangeValid()) is validated but no longer described, unless the block constrains it; reading the descriptors also means a composed constraint is described with its @OverridesAttribute applied;
    • grails-openapi gets BeanValidationSchemaSpec (the fixture now builds the registry through ValidatorRegistries, as the datastores do), and the upgrade note mentions the OpenAPI descriptions next to scaffolding and the fields plugin.

Run locally: PersistentEntityValidatorSpec, the jakarta specs of grails-datamapping-core, the DataTest spec, EntityValidatorDomainPropertySpec (grails-fields, new case through JakartaValidatorRegistry), the grails-openapi suite, and the TCK BeanValidationSpec on Hibernate 5, Hibernate 7 and MongoDB. Neo4j is left to CI.

@jamesfredley on the fields plugin (DomainPropertyImpl line 57):

Addressed by the design change rather than an edit to DomainPropertyImpl: the validator of an annotated entity is now a PersistentEntityValidator subclass, so the instanceof check on line 57 passes and the fields plugin reads the merged constraints as they are. EntityValidatorDomainPropertySpec has a new case that builds the validator through JakartaValidatorRegistry and checks isRequired() and constrained.maxSize for an annotated class. The same holds for PersistentGraphQLProperty and for any plugin outside this repository that checks the type.

The three inline threads have their own replies.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The four earlier comments are fixed. Cascading invokes the associated validator, a grouped @NotNull no longer relaxes ordinary nullable: false, the registry returns a PersistentEntityValidator subclass so the fields plugin can see the constraints, and composed constraints use the provider descriptors so @OverridesAttribute is kept. This was not a rebase: the new head changes 34 files on the same parent. Not approving yet because default group sequences that extend another group are still filtered by exact group membership.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Second review of #16624 at d3f8ba5600 (base 8.0.x). It is one commit on e4b22127dc6, 16 commits behind the current 8.0.x tip 956b3e719d, and git merge-tree against the tip is clean. git range-diff shows that d3f8ba5600 is 74cebef5fc rebased, with only the upgrade note renumbered from 87 to 89. I reviewed the changes from 280375075f to 74cebef5fc.

What I ran and checked:

  • Tests at the head, all green:
    • :grails-datamapping-validation:test: 61 tests.
    • :grails-datamapping-core:test: 1817 tests.
    • :grails-testing-support-datamapping:test.
    • :grails-openapi:test: 297 tests.
    • :grails-fields:test: 699 tests.
    • The full :grails-data-hibernate5-core:test: 1144 tests.
    • The validation specs on Hibernate 7, MongoDB and Neo4j.
    • The new TCK BeanValidationSpec ran all 7 features on Hibernate 5, Hibernate 7, MongoDB and Neo4j.
    • :grails-datamapping-core-test:test, the simple-datastore TCK suite: 687 tests. The 7 BeanValidationSpec features are skipped there, as intended.
  • Style: codeStyle on the six changed modules is clean.
  • Probe specs from my first review, not committed, run again at this head with DataTest and with a real Hibernate 5 HibernateDatastore. I added three cases: a class-level constraint on an associated domain class, @Valid on an association to an annotated class, and a hasOne to an annotated class.
  • CI: the PR has the no ci label, so no workflow ran on d4f19e4a3f, 74cebef5fc or this head. That includes the Neo4j run the reply leaves to CI; I ran it locally (above).

All four points from my first review are fixed, and the smaller points are too. Making the annotated entity's validator a PersistentEntityValidator subclass is a better split than the adapter. Every instanceof PersistentEntityValidator consumer now sees the merged constraints, and GormValidatorAdapter is unchanged from 8.0.x. One new edge case in the cascade (1) is worth fixing before merge; the rest are optional.

The first review's findings

Probe 280375075f this head
Annotated parent with an annotated child (DataTest, and Hibernate 5 with and without @Valid) valid, nothing checked on the child children[0].label: NotBlank, children[0].code: nullable
Plain parent with an annotated child valid the same two errors
@NotNull(groups = OnCreate) with nullable: false in the block valid, but the metadata says required nullable error, metadata says required
Cross-field @AssertTrue boolean isRangeValid() AssertTrue error; rangeValid described with inList: [true] AssertTrue error; not described
Class-level @OrderedRange on the validated domain class (Hibernate 5) OrderedRange (as on 8.0.x) OrderedRange

The new cases:

  • With @Valid on the association, the child's annotation error is reported once.
  • A hasOne to an annotated class reports detail.label (NotBlank) and detail.code (nullable).

Point 3 is done as well. The upgrade note separates the rules that shaped the schema from the ones that are new, and it names the global default constraints. The class-level bullet is gone, and neither the commit message nor the description repeats the claim.

1. A class-level constraint on an associated domain class is reported on the field ranges[0].

@Entity
class Parent {
    @NotNull String name
    static hasMany = [ranges: RangeChild]
}

@Entity
@OrderedRange   // class-level: low <= high
class RangeChild {
    @NotNull String label
    Integer low
    Integer high
    static belongsTo = [parent: Parent]
}

def p = new Parent(name: 'p')
p.addToRanges(new RangeChild(label: 'x', low: 5, high: 1))
p.validate()                          // false, correctly
p.errors.fieldErrors*.field           // ['ranges[0].']
p.errors.hasFieldErrors('ranges[0]')  // false

The cascade runs the child's Bean Validation with the nested path ranges[0]. set (PersistentEntityValidator.groovy:317). SpringValidatorAdapter.processConstraintViolations builds the field as bindingResult.getNestedPath() + field, and the field of a class-level violation is empty. On the validated object itself the result is empty, so the violation becomes a global error, which is the case the TCK spec checks (BeanValidationSpec.groovy:148). Under a nested path, the field is the path itself with the separator still on the end.

As a result:

  • g:hasErrors and getFieldError('ranges[0]') don't find the error.
  • A JSON error response shows "field": "ranges[0].".

When Spring cascades through @Valid itself, determineField gives ranges[0] for the same violation. I'd report it there and add the associated case to the TCK spec next to the existing one. errors.rejectValue('', code, args, message) under that nested path already resolves to ranges[0], so JakartaPersistentEntityValidator.validateBeyondConstraints (:95) could treat a violation with an empty field that way when the nested path isn't empty.

2. Smaller points

  • Upgrade note, MongoDB and Neo4j (upgrading80x.adoc:4874):
    • "already enforced at flush time" holds for Hibernate with a schema generated from the mapping.
    • On 8.0.x, every datastore gave an annotated domain class a GormValidatorAdapter alone. MongoDB and Neo4j have no schema, so for them nullable and maxSize from the block are enforced for the first time as well.
    • The same holds for the nullable: false that grails.gorm.default.nullable = false gives every unannotated property. On those datastores, every such property of an annotated class now becomes required in validate().
    • A sentence saying so would help MongoDB users in particular.
  • Message codes of a cascaded annotation error (beanValidation.adoc:45, :49):
    • The class-qualified codes of a cascaded Bean Validation error name the validated class and the path: NotBlank.com.example.Invoice.lines[0].label and NotBlank.com.example.Invoice.lines.label.
    • The block's codes for the same line keep the line's class: com.example.InvoiceLine.sku.nullable….
    • So a message keyed NotBlank.com.example.InvoiceLine.label applies when the line is validated on its own, but not through the invoice. NotBlank.lines.label, NotBlank.label and NotBlank work both ways.
    • Spring's nested validation names them the same way, so a sentence in the guide is enough.
  • no ci label: please remove it before merge so the final head gets a full CI run.

Verified as correct

  • Validator split:
    • JakartaValidatorRegistry registers a JakartaPersistentEntityValidator for an entity carrying @Validated, and the plain PersistentEntityValidator for every other entity.
    • For a plain entity, getValidatedConstrainedProperties() returns the same map as before and validateBeyondConstraints does nothing. So validation of unannotated domain classes is unchanged.
    • The consumers that check for a PersistentEntityValidator:
      • the cascade itself;
      • DomainPropertyImpl in grails-fields;
      • PersistentGraphQLProperty, which reads only order from it.
  • Cascade:
    • The associated entity is validated with the constraints its validator validates, not the ones it exposes, so the translated metadata isn't checked a second time.
    • Bean Validation runs once per associated object, inside the existing validatedObjects guard, and never cascades on its own (validate(obj, errors, false)).
    • deepValidate: false skips the associated objects.
  • Groups:
    • The translator reads the BeanDescriptor and keeps the constraints whose groups intersect the default group.
    • When the class redefines the default group with @GroupSequence, the groups the sequence's groups extend and the groups of a nested sequence count too.
    • The TCK BeanValidatedArticle case covers that on all four datastores.
  • Composed constraints: they are described from the provider's descriptors, so an @OverridesAttribute is applied (JakartaConstraintsTranslatorSpec, maxSize == 7).
  • Tests:
    • The TCK spec replaces the Hibernate 5 and Hibernate 7 copies. It is skipped in the simple-datastore suite through simple.gorm.suite (grails-datamapping-core-test/build.gradle:145).
    • OpenApiFixture now builds the registry the datastores use, and the whole grails-openapi suite passes with it.
    • The new files have the license header and no @author.
  • Docs:
    • link:validation.html#constraints resolves to the Declaring Constraints section.
    • The upgrade note is number 89, after 88 on the current 8.0.x tip.

@jdaugherty
jdaugherty force-pushed the fix/gorm-bean-validation-constraints branch from d3f8ba5 to cbfe65b Compare October 28, 2026 21:52
@jdaugherty jdaugherty removed the no ci label Oct 28, 2026
@jdaugherty
jdaugherty force-pushed the fix/gorm-bean-validation-constraints branch from cbfe65b to 051efbe Compare October 28, 2026 21:52
@jdaugherty

Copy link
Copy Markdown
Contributor Author

Thanks for the second pass. The cascade edge case and the two smaller points are addressed in 051efbe (diff against d3f8ba5600).

1. A class-level constraint on an associated domain class

The fix is in GormValidatorAdapter, not in JakartaPersistentEntityValidator.validateBeyondConstraints:

  • The field is built inside SpringValidatorAdapter.processConstraintViolations.
  • The hooks that build the code and the arguments (determineField, determineErrorCode, getArgumentsForConstraint) are protected, so only a subclass of the adapter can report the violation differently.

The adapter now overrides processConstraintViolations, and the override acts only when the errors have a nested path:

  • A violation with an empty field is reported with rejectValue('', …), so it lands on ranges[0]. Its arguments are built for that path.
  • Property violations still go through Spring unchanged.
  • Without a nested path nothing changes, so a class-level violation of the validated object is still a global error.

Regressions:

  • TCK BeanValidationSpec (run locally on Hibernate 5, Hibernate 7, MongoDB and Neo4j): BeanValidatedPair is now owned by a plain BeanValidatedPairing. A pair violating its class-level @DistinctLabels makes the pairing report exactly one field error, on pairs[0].
  • GormValidatorAdapterSpec: validates a PriceRange under the nested path range. It compares the error with the one Spring reports when it cascades from the holder through @Valid, with the same field, codes, arguments and message. It also pins the global error of the validated object.

Both fail without the adapter change.

2. Smaller points

  • Upgrade note:
    • Flush-time enforcement of nullable, unique and maxSize is now stated for a schema that GORM for Hibernate generated from the mapping.
    • With GORM for MongoDB and GORM for Neo4j, nullable and maxSize are enforced for the first time. This includes the nullable: false that grails.gorm.default.nullable = false gives every property without a nullability rule of its own.
  • Message codes: the guide now says that the codes of an annotation error found through an association name the validated class and the path, while the codes of the block keep the class of the associated instance. So NotBlank.com.example.InvoiceLine.label applies only to a line validated on its own, while NotBlank.lines.label, NotBlank.label and NotBlank apply both ways. It also says that a class-level constraint of the associated class is reported on the association path itself.
  • no ci label: removed, so this head gets a full CI run.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not approving. A ConvertGroup on a cascaded association is validated in the default group, a superclass GroupSequence is ignored on a subclass, and an inclusive decimal bound on an integer property is dropped from the described constraints. This is a bugfix, so 8.0.x can keep it.

@jdaugherty

jdaugherty commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@jamesfredley Thanks. All three are fixed in 491fca0 (diff against 051efbe12c).

1. @ConvertGroup on a cascaded association

There is still one cascade, GORM's, and the groups now travel down it:

  • PersistentEntityValidator carries validation hints (Spring's term; for Bean Validation, the groups) from each object to its associations.
    • The validator of the entity that owns an association gives the hints for the associated object (getAssociationValidationHints).
    • The validator of the associated entity receives them in getValidatedConstrainedProperties and validateBeyondConstraints.
    • The root object has no hints, which means the default group.
  • For an association marked @Valid, JakartaPersistentEntityValidator returns the owner's groups converted by the association's @ConvertGroup, read from its PropertyDescriptor or from a cascaded container element. That is how Bean Validation cascades. Any other association gets the default group, the same as when the object is validated on its own.
  • The nullable relaxation follows the same groups. Under the converted group, nullable gives way to the annotations of that group that declare nullability. A default-group @NotNull that the converted group doesn't run leaves the block in force. A null is still reported once, and the block still rejects a null that the annotations no longer check.

Your example now reports child.label (NotBlank). When the child is reached through a conversion, its default-group annotations aren't checked, which is what Bean Validation's own cascade does.

One correction on "the provider used to follow @Valid": on 8.0.x it never cascaded. MappingContextTraversableResolver.isCascadable walks the path to the traversable object, and the root node of that path has no name, so it returned false. A probe on e4b22127dc accepts your example. Even a plain Hibernate Validator run with that resolver reports nothing through @Valid, whether into an association or into a non-entity object. @matrei saw the same in the first review. So honoring the conversion is new behavior rather than a restoration, but it is the right behavior.

Regressions:

  • TCK BeanValidationSpec: BeanValidatedPost has @Valid @ConvertGroup(from = Default, to = PublishChecks) BeanValidatedTeaser teaser. It reports teaser.label (NotBlank) and teaser.note (nullable, from the block, because the teaser's default-group @NotNull isn't run).
  • JakartaValidatorRegistrySpec:
    • a conversion on a hasMany;
    • propagation along a nested @Valid;
    • the default group along a plain association;
    • the same book validated on its own.
  • PersistentEntityValidatorSpec:
    • the hints reach each level and propagate two levels down;
    • a validation started mid-cascade starts without hints and leaves the outer one intact.

2. A superclass @GroupSequence

I didn't take "the sequence of the class that declares the constraint" literally, because Hibernate Validator doesn't work that way (ValidatorImpl.validateConstraintsForDefaultGroup). Walking up from the validated class, the first class that redefines the default group applies its sequence to its own constraints and to those of its superclasses, and stops there. Constraints of the classes below it are validated in Default only. So:

  • A subclass without a sequence: the superclass's sequence covers the superclass's annotations, but not the subclass's own @Null(groups = PublishChecks).
  • A subclass with its own sequence: that sequence covers every class above it, and the superclass's sequence is ignored.

JakartaConstraintsTranslator now reads each class's own constraints (Scope.LOCAL_ELEMENT on that class's descriptor, in the provider's hierarchy order) and applies this rule.

Regressions:

  • JakartaConstraintsTranslatorSpec: one feature for each case. Each first asserts what Hibernate Validator itself reports for the same instances.
  • TCK BeanValidationSpec: BeanValidatedRecall extends BeanValidatedNotice, which has @GroupSequence([DraftChecks, BeanValidatedNotice]). The superclass's headline is reported once (NotNull), and the subclass's reason by the block.

3. Decimal bounds on integer properties

An inclusive @DecimalMin is now rounded up and an inclusive @DecimalMax rounded down before the conversion, as the exclusive bounds already were. @DecimalMin('1.5') @DecimalMax('4.5') Integer quantity is described as min: 2, max: 4. The translator spec covers inclusive, exclusive, negative and whole bounds, and checks each one against what Hibernate Validator accepts at and beyond the bound.

Docs

  • Guide: covers the superclass sequence, @ConvertGroup on an association marked @Valid, and @DecimalMin/@DecimalMax.
  • Upgrade note: the cascade bullet mentions the conversion.

Run locally

  • Module tests:
    • :grails-datamapping-validation:test: 62 tests.
    • :grails-datamapping-core:test: 1827 tests.
    • :grails-testing-support-datamapping:test: 9 tests.
    • :grails-openapi:test: 297 tests.
    • :grails-fields:test: 699 tests.
  • TCK BeanValidationSpec: all 10 features pass on Hibernate 5, Hibernate 7, MongoDB and Neo4j. The two new features fail on the main sources of 051efbe (checked on Hibernate 5).
  • Style: codeStyle on grails-datamapping-core, grails-datamapping-validation and grails-datamapping-tck is clean.

…asses and expose their constraints

A domain class carrying a jakarta.validation annotation is validated by
Hibernate Validator through GormValidatorAdapter, which until now replaced
GORM's own validator entirely: the constraints block was ignored for
validation while it still defined the schema, the validator exposed no
constraint metadata (it was not a PersistentEntityValidator, so
constrainedProperties was empty for scaffolding and plugins, and
validation cascading into such a class checked nothing), null values were
never reached by @NotNull and friends because the traversable resolver
treated a null property as uninitialized, and the unit test datastore
ignored the annotations altogether.

JakartaValidatorRegistry now registers a JakartaPersistentEntityValidator
for an annotated entity: a PersistentEntityValidator that validates the
constraints block, cascades to the associations like any other, and then
validates the annotations with Bean Validation, which no longer cascades
itself. PersistentEntityValidator gains the validateBeyondConstraints hook
the subclass implements, called for the root object and for each
associated object under the path of its association, and validates an
associated entity with the constraints its validator validates rather than
the ones it exposes. Validation hints travel down the cascade: the
validator of the entity owning an association gives the hints of the
associated object (getAssociationValidationHints), and the validator of
the associated entity validates it with them. An object associated through
a property marked @Valid is thus validated in the groups of its owner,
converted as @ConvertGroup declares, as Bean Validation cascades, and any
other associated object in the default group, as on its own. The GORM
nullable constraint is relaxed for a property whose nullability an
annotation of the validated groups declares, so a null value is reported
once; an annotation of another group leaves the block in force.

The exposed constraints merge the block with a description of the
annotations (JakartaConstraintsTranslator), read from the Bean Validation
descriptors of the class and of its superclasses, so that a composed
constraint carries its attribute overrides. Only the default group is
described: as Hibernate Validator applies it, the first class from the
class up to redefine the default group with a @GroupSequence applies the
sequence (with the groups those extend and the groups of a nested
sequence) to its own constraints and to the ones of its superclasses,
while the classes below it validate theirs in the Default group. A decimal
bound of an integer property is described as the nearest whole number it
admits, and a getter without a backing field is left out. Every consumer
that looks for a PersistentEntityValidator, such as the fields plugin, the
GraphQL properties and the OpenAPI descriptions, sees the merged
constraints without a change.

MappingContextTraversableResolver treats a null value as reachable.
GormValidatorAdapter reports a class level violation found under a nested
path, as for an associated object, on the path itself (lines[0]), as
Spring does when Bean Validation cascades through @Valid.
DataTest creates the same validator for annotated domain classes. The
Hibernate 5 and 7 specs are replaced by one TCK spec that runs on every
datastore.

Documented in a new Bean Validation Annotations section of the validation
guide and in the 8.0.x upgrade notes.
@jdaugherty
jdaugherty force-pushed the fix/gorm-bean-validation-constraints branch from 41c275b to 491fca0 Compare October 29, 2026 02:11
…7 apps

The grails-hibernate test apps of Hibernate 5 and Hibernate 7 gain Ticket
and TicketNote, domain classes constrained with Bean Validation annotations
only. TicketValidationSpec checks in the running application that save()
and validate() report the annotations, a null required by an annotation
included, that save(failOnError: true) throws, that a valid ticket is saved
with its notes, that validation cascades to the notes, that an invalid
update is rejected and nothing of it is written, that the annotations are
described by Ticket.constrainedProperties, and that their errors are
resolved through the message source. TicketControllerSpec posts forms to a
controller that binds and saves a ticket, and checks over HTTP that an
invalid form is rejected with the resolved errors and a valid one stored.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A ConvertGroup on one association is validated in the converted group, a superclass GroupSequence is applied on a subclass, and an inclusive decimal bound on an integer is kept. Not approving. Two associations of the same child still validate only the first converted group, and a GroupSequence is not expanded before the next ConvertGroup. This is a bugfix, so 8.0.x can keep it.

…hared associations

JakartaPersistentEntityValidator is a SmartValidator again, as the adapter
it replaced was: PersistentEntityValidator validates with the validation
hints Spring's DataBinder and ValidationUtils pass, and an annotated entity
validates in the groups among them, cascading with them.

A @ConvertGroup conversion applies to the groups the provider validates
when a group of the owner is validated, so a sequence an earlier conversion
targets is expanded, in its order, before the conversions of a nested
association apply, and a group brings the groups it extends. A sequence
none of whose groups is converted is passed on as it is, so it still stops
at its first group with a violation.

An associated instance reached through two associations is validated once
with each list of groups it is reached with, instead of once in the groups
of the first association.

Regressions in PersistentEntityValidatorSpec, JakartaValidatorRegistrySpec
and the TCK BeanValidationSpec. The validation guide and upgrade note 89
describe the hints and the expansion of the groups.
…rted groups along the provider's cascade

PersistentEntityValidator.cascadeValidationToOne unwraps a proxy before validating the associated
object, as validate() does for the object it starts with: the visited set, the cascade decision and
the validators see the instance, which holds the fields Bean Validation reads and which a cycle of
associations has to end at however it is reached. An initialized proxy of a valid annotated instance
was read as the proxy, whose fields are null, so @notblank and the other annotations failed on it.

GormValidatorAdapter.validate(obj, errors, cascade, groups, reportedGroups) decides for each
violation whether it is reported, with the reported groups converted along the path of the violation
as the @ConvertGroup annotations of each property the provider cascaded through declare, the way the
provider converts the groups it validates in: a converted group as the group it converts to with the
groups that one extends or sequences, an unconverted group alone, and the default group of a bean as
the groups of the sequence redefining it, which the adapter expands for every bean rather than the
entity validator for the root alone. A transient property marked @Valid that converted a reported
group of the entity to another group had its violations discarded, so the entity was accepted with
invalid details. JakartaConstraintsTranslator exposes defaultGroupsOf and cascadedDescriptorOf for
both.

Regressions: PersistentEntityValidatorSpec (a Javassist proxy reached through a to-one and through a
collection is validated once, as the lamp behind it), JakartaValidatorRegistrySpec (a proxy of an
annotated book reports no false NotBlank and a violation of the book with the value of the book;
transient details converting Extended to DetailsChecks, checked against Hibernate Validator's own
result), GormValidatorAdapterSpec (the conversion and the default group of a cascaded bean) and the
TCK BeanValidationSpec (a proxy from proxy(id), initialized, as the book of a shelf), each failing
without the fix. The guide and the upgrade note describe both.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

An associated proxy is validated as the instance behind it, and a converted group on a transient @Valid child is kept. Not approving. A nested validation drops the enclosing cascade flag, a declared Object still hides the runtime conversion, and a dynamic group sequence is frozen from the static annotations.

…es to and the groups a sequence provider chooses

A validation started while another one is in progress, such as by a custom constraint validating another domain
instance with validate(), removed the CASCADE_VALIDATION flag of the enclosing validation when it ended, so the
provider stopped cascading through the transient properties marked @Valid of the objects it reached, and cascaded
into the persistent associations of the entity again. GormValidatorAdapter now puts the value of the enclosing
validation back in each overload.

The filter of the reported groups walked the declared types of the properties the provider cascaded through, so a
transient property declared as an Object hid the @ConvertGroup of a property of the value it held, and a violation
found through the converted group was dropped. It now reads the beans the provider cascaded to from the validated
object, the element of a container by its index or key, and uses their classes; an element of a set, which the path
does not identify, is still read as the declared type.

The nullability constraints of the block left to Bean Validation were decided from the static annotations alone,
whereas Hibernate Validator's @GroupSequenceProvider chooses the default group sequence per instance, so
`nullable: false` with a @null of a group the provider chose for the instance rejected a value the provider
accepted. JakartaConstraintsTranslator treats a class with the provider as redefining the default group, describes
it with the sequence the provider gives for no instance, as its descriptor does, and finds the default groups of an
instance (findDefaultGroups); PersistentEntityValidator passes the object to getValidatedConstrainedProperties, so
JakartaPersistentEntityValidator relaxes the nullability constraints per the groups of the instance, and the adapter
expands the default group of each bean it reads along a path for that bean.

Regressions in GormValidatorAdapterSpec, JakartaValidatorRegistrySpec, JakartaConstraintsTranslatorSpec and the TCK
BeanValidationSpec (BeanValidatedLedger with its counterpart, BeanValidatedMember with its sequence provider), all
failing without the changes. The guide and upgrade note 89 describe the three behaviours.

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Two rounds, a commit each, as before.

At 837f6d9, for the review at 15689b8 (two threads). A fifth commit.

  • An initialized proxy of an associated instance was validated as the proxy (thread on cascadeValidationToOne). The cascade unwraps the associated object before anything else, as validate() does for the object it starts with, so the visited set, the cascade decision and the validators all see the instance: the provider reads its fields, which the proxy does not carry, and a cycle of associations ends at the instance however it is reached. Regressions: PersistentEntityValidatorSpec (a Javassist proxy reached through a to-one, then through a collection next to the instance itself, is validated once, as the lamp behind it), JakartaValidatorRegistrySpec (a proxy of a valid annotated book reports nothing, and once the book is invalid the violation carries the value of the book, not null) and the TCK BeanValidationSpec (BeanValidatedShelfBook.proxy(id), initialized after a session.clear(), as the book of a shelf). All fail without the fix, the TCK one on Hibernate 5 with a HibernateProxy.
  • A converted group on a transient @Valid child was dropped (thread on the adapter). GormValidatorAdapter decides for each violation whether it is reported with the groups in effect for the bean holding the constraint: the reported groups of the validated object, converted along the path of the violation as the @ConvertGroup annotations of each property the provider cascaded through declare, the way validateCascadedAnnotatedObjectForCurrentGroup converts them, a converted group as the group it converts to with the groups that one extends or sequences, an unconverted group alone. The default group of a bean stands for the groups of the sequence redefining it, which the adapter now expands for every bean rather than the entity validator for the root alone. In the path of a violation the last node is the constrained element (a property, a container element or the bean node of a class level constraint) and the nodes before it are the cascaded properties, so the walk covers cascaded properties, cascaded container elements and class level constraints of cascaded beans alike. Regressions: JakartaValidatorRegistrySpec (your case, ExtendedChild with transient details converting Extended to DetailsChecks: validated in Extended, the owner reports child.details.summary and not the Base violation of the details, and nothing in Base, both as Hibernate Validator does) and GormValidatorAdapterSpec (the conversion along the path, and the redefined default group of a cascaded bean and of the validated object). All fail without the fix.

The guide and the upgrade note say that a transient @Valid property is cascaded to in the groups of its owner, converted as its @ConvertGroup annotations declare, and that an initialized proxy of an associated instance is validated as the instance.

Run locally: :grails-datamapping-core:test (1845), :grails-datamapping-validation:test (66) and :grails-testing-support-datamapping:test (10); the TCK BeanValidationSpec, 18 features, on Hibernate 5, Hibernate 7, MongoDB and Neo4j (Docker), with the grails.gorm.tests.validation specs of both Hibernate versions; codeStyle on grails-datamapping-core, grails-datamapping-validation and grails-datamapping-tck.

At 1bd4754, for the review at 837f6d9 (three threads). A sixth commit.

  • A nested validation wiped the cascade flag (thread on the overloads of GormValidatorAdapter). Each validate overload now remembers the value of CASCADE_VALIDATION it found and puts it back when it ends, removing it only when there was none, so a custom constraint validating another domain instance with validate() leaves the enclosing validation cascading as it did. The original three-argument overload leaked the same way and got the same treatment. Regressions: GormValidatorAdapterSpec (the flag a constraint validating an issuer with the adapter sees before and after its own validation), JakartaValidatorRegistrySpec (your case: with the auditor validated by its constraint in between, details.leaf.label is still reported) and the TCK BeanValidationSpec (BeanValidatedLedger, whose @ValidCounterpart calls counterpart.validate(); the counterpart is owned without a reference back, as a validation of it would otherwise cascade to the ledger, whose constraint validates it again, without end).
  • The walk of the path used the declared types (thread on isReported). The adapter now reads the beans the provider cascaded to from the validated object, following each property node and, for an element of a container, the index or key of the next node, and looks up the descriptor, the conversions and the default groups of the class of each bean; the leaf bean comes from the violation as before. Only an element of a set, which the path does not identify, is still read as the declared type. Regressions: GormValidatorAdapterSpec (Stamp.attachment, declared as an Object, converting ExtendedGroup to DetailGroup for its details) and JakartaValidatorRegistrySpec (your case: ExtendedChild.record, an Object holding a record that converts Extended to DetailsChecks for its details; validated in Extended, the owner reports child.record.details.summary, as the provider does).
  • A @GroupSequenceProvider was frozen to the static annotations (thread on getValidatedConstrainedProperties). JakartaConstraintsTranslator treats a class with the provider as redefining the default group, as validateConstraintsForDefaultGroup does: the class is described with the sequence the provider gives for no instance, as its BeanDescriptor is, and findDefaultGroups(instance) gives the groups of the sequence the provider chooses for an instance. PersistentEntityValidator.getValidatedConstrainedProperties now receives the object, so JakartaPersistentEntityValidator relaxes the nullable constraints with the groups of the instance, keyed with the groups and the excluded groups, and the adapter's filter expands the default group of each bean it reads for that bean. Regressions: JakartaConstraintsTranslatorSpec (the static and the per-instance groups of ProvidedProduct), JakartaValidatorRegistrySpec and the TCK BeanValidationSpec (your case, nullable: false with @Null(groups = RetiredChecks): an active member without a desk gets nullable, a retired one is valid, as the provider says, and a retired one with a desk gets Null; the constrainedProperties describe the class for no instance, so desk stays required there).

All eight new features fail without the changes, every other test passing. The guide and the upgrade note say that a transient @Valid property is cascaded to as the value it holds, whatever its declared type, that a custom constraint may validate another domain instance while its owner is validated, and that a domain class with @GroupSequenceProvider is validated, and its nullable constraints relaxed, in the sequence the provider chooses for the instance.

Run locally: GormValidatorAdapterSpec, JakartaValidatorRegistrySpec, JakartaConstraintsTranslatorSpec, MappingContextTraversableResolverSpec and PersistentEntityValidatorSpec; :grails-datamapping-validation:test and :grails-testing-support-datamapping:test; the TCK BeanValidationSpec, 20 features, on Hibernate 5, Hibernate 7, MongoDB and Neo4j (Docker); the fields EntityValidatorDomainPropertySpec and the openapi BeanValidationSchemaSpec; codeStyle on grails-datamapping-core, grails-datamapping-validation and grails-datamapping-tck.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fourth review of #16624 at 1bd4754bbd (base 8.0.x). Three commits since my third review at 237bf12e59: 15689b8f9f, 837f6d9348 and 1bd4754bbd. The branch is still on e4b22127dc and is now 179 commits behind the 8.0.x tip 4ffebc51f2. git merge-tree against the tip is clean.

What I ran and checked:

  • Tests at the head, all green:
    • :grails-datamapping-validation:test: 66 tests.
    • :grails-datamapping-core:test: 1852 tests.
    • :grails-testing-support-datamapping:test: 10 tests.
    • :grails-fields:test: 699 tests, and :grails-openapi:test: 306 tests.
    • The TCK BeanValidationSpec, all 20 features, on Hibernate 5, Hibernate 7, MongoDB and Neo4j, with the grails.gorm.tests.validation specs on both Hibernate versions.
    • :grails-datamapping-core-test:test: 700 tests, with BeanValidationSpec skipped as intended.
    • TicketValidationSpec and TicketControllerSpec in both grails-hibernate test apps: 10 tests each.
  • Style: codeStyle is clean on grails-datamapping-core, grails-datamapping-validation, grails-datamapping-tck and grails-testing-support-datamapping.
  • Probe specs, not committed: run at this head and on e4b22127dc, each case compared with what a plain Hibernate Validator reports for the same instances.
  • CI: at this head, 36 checks had passed and 54 were still pending when I checked, with no failures. TestLens reported 118,015 tests passing on 837f6d9348.

All four points of my third review are fixed, each with regression tests. James's threads from his three reviews since then all have fixes and regression tests too.

I'd like the PR retargeted to 9.0.x (see "Target branch" below). One problem is left in the code (1). It comes from the cycle guard keyed on validation hints that 237bf12e59 added, and I missed it last round. 2 and 3 are smaller.

Target branch: 9.0.x rather than a patch release

You offered in the description to move this to 9.0, and I think that's the right call. RELEASE.md defines a patch as a backward-compatible bug fix that "should involve no work", and even a minor as "little to no work to upgrade". By that measure this isn't a patch:

  • It changes which data validates. The upgrade note this PR adds says the new rules "may reject data that 8.0.0 saved", and asks users to review the constraints block and the global default constraints of each annotated domain class. On MongoDB and Neo4j, every property of such a class that declares no nullability of its own becomes required.
  • It adds features and API:
    • validation groups through SmartValidator;
    • @ConvertGroup and group sequences across GORM's cascade, and @GroupSequenceProvider;
    • the annotations described in constrainedProperties for scaffolding, the fields plugin and OpenAPI;
    • new protected hooks on PersistentEntityValidator.
  • It changes the cascade of every domain class, annotated or not, and every review round so far has found a regression there. A major release gives that its milestones and release candidates before it reaches production apps.

Moving it is cheap:

  • 9.0.x already contains e4b22127dc, and git merge-tree against it is clean, so changing the base branch should be enough.
  • The upgrade note would move to upgrading90x.adoc, and the @since 8.0.1 tags would become 9.0.0.

If a fix is wanted in 8.0.x as well, the null fix could go there on its own: @NotNull, @NotBlank and @NotEmpty never saw a null value. That annotation clearly promised it, and the fix in MappingContextTraversableResolver is small.

1. A cycle of associations leads back to an instance validated with hints, which is validated again

interface OnPublish {}

@Entity
class Account {
    @NotBlank(groups = OnPublish) String summary
    @NotNull String owner
    Region region
}

@Entity
class Region {
    String name
    Office office
}

@Entity
class Office {
    String city
    Account account
}

def account = new Account(summary: '', owner: null)
account.region = new Region(name: 'r', office: new Office(city: 'c', account: account))
ValidationUtils.invokeValidator(validator, account, errors, OnPublish)
// Hibernate Validator in OnPublish: summary (NotBlank)
// 8.0.x:                            summary (NotBlank)
// this head:                        summary (NotBlank), region.office.account.owner (NotNull)

A plain entity does the same. Replace the annotations with static constraints = { owner nullable: false } and validate with any hint: the head reports owner and region.office.account.owner, both nullable, where 8.0.x reports owner once.

The cause:

  • validate() adds the instance it starts with as ValidatedObject(target, hints) (PersistentEntityValidator.groovy:135).
  • cascadeValidationToOne keys an associated instance on the hints its owner gives the association (line 419). Those are none for an association that isn't marked @Valid, and none for every association of a plain entity.
  • So when the account was validated with hints, the cycle reaches it again as (account, []). That key isn't in the set, and the account is validated again in the default group under the nested path, both its block and its annotations.

On 8.0.x, a cycle always ended at the instance validation started with (validatedObjects.contains).

It takes validation hints, so ValidationUtils.invokeValidator(validator, instance, errors, hints) or DataBinder.validate(hints). validate() and save() aren't affected. For a plain entity it changes existing calls as well: on 8.0.x its validator wasn't a SmartValidator, so Spring dropped the hints.

Ending a cycle at the instance validation started with, whatever hints it's reached with, would restore the 8.0.x behaviour. For example, Cascade could hold that instance, and cascadeValidationToOne could return early when instance.is(root). Keying the instance on the hints its own validator acts on, which are none for a plain entity, would fix only the plain case. A regression case for each kind of entity would pin it down.

2. A @Valid association of an entity reached through a transient property isn't validated

@Entity
class Holder {
    @NotBlank String name

    @Valid Featured featured

    static transients = ['featured']
}

@Entity
class Featured {
    @NotBlank String title
    @Valid Author author
}

@Entity
class Author {
    @NotBlank String name
    static belongsTo = [Featured]
}

new Holder(name: 'h', featured: new Featured(title: '', author: new Author(name: '')))
// Hibernate Validator: featured.title, featured.author.name
// this head:           featured.title
// 8.0.x:               neither

It isn't a regression, but the guide says the provider cascades to the value of a transient @Valid property, "and so is each value it cascades to in turn" (beanValidation.adoc:49).

The cause:

  • While GORM cascades, MappingContextTraversableResolver.isCascadable (line 84) refuses the persistent associations of every bean it's asked about.
  • That includes featured, a bean the provider reached through a transient property and GORM never reaches, so nothing validates its author.

Refusing them only on the root bean of the provider's validation, the instance GORM itself is validating, would let the provider cascade from there. Otherwise the guide sentence could be narrowed.

3. A subclass instance passed to the validator of its superclass is validated with the superclass's rules

supports now accepts subclasses (PersistentEntityValidator.groovy:514), so a proxy passes Spring's check. But so does a subclass that is an entity of its own. For example, Document is a plain entity and Report extends Document has pages nullable: false. With pages null:

  • ValidationUtils.invokeValidator(documentValidator, report, errors) reports nothing, where the report's own validator reports pages (nullable).
  • 8.0.x threw an IllegalArgumentException because the validator didn't support the class.

The guide (beanValidation.adoc:68) and the upgrade note (upgrading80x.adoc:4882) say the validator supports the subclasses. Once validate() has unwrapped the instance, it could hand one whose class is another entity to that entity's validator.

Verified as correct

  • The four points of my third review:
    • Instances are compared by identity: ValidatedObject and ValidatedConstraints use is() and System.identityHashCode. The basket case now reports lines[1].code, as on 8.0.x.

    • isBeanValidated asks the provider. A subclass without annotations of its own, a class whose only constraint is a class-level one, and an owner without constraint annotations whose @Valid @ConvertGroup association converts Default all report what Hibernate Validator reports. getValidator caches the decision, DataTest asks the validator factory of the test context, and nothing else keys on @Validated (the transformer still adds it).

    • Sequences are validated step by step over the graph. The Owner/Child/Grandchild case reports child.grandchild.x alone, and child.b once the grandchild is valid, as Hibernate Validator does. This matches validateInContext:

      • the groups that aren't sequences come first, together;
      • then each sequence goes group by group and stops when the violation count grows.

      A violation of an associated instance's constraints block counts toward the group the instance is first reached in, and the guide says so.

    • The guide's cascade paragraph is split into paragraphs and a list, the SmartValidator paragraph shows getEntityValidator, the upgrade note's bullet is split up, and the two test apps use the org.apache.grails coordinates.

  • James's threads: I read the fixes and their regression tests, which check Hibernate Validator's result first.
    • Proxies are unwrapped in validate() and in cascadeValidationToOne, while an uninitialized to-one proxy is still skipped by cascadeToAssociativeProperty.
    • The provider cascades through a transient @Valid property.
    • The excluded groups of an extended group are left out.
    • OR compositions aren't described.
    • All three overloads of the adapter restore the cascade flag.
    • isReported follows the runtime beans.
    • @GroupSequenceProvider is supported.
  • Plain entities otherwise behave as before:
    • Splitting validate() into validateConstraints and validateAssociationsAndBeyond keeps the order of the errors: an owner's name, then items[0].code, as on 8.0.x.
    • The inverse side of the association an instance was reached through is still skipped, and so are the excluded properties of an embedded association.
    • beforeValidate runs once for each associated instance.

@jdaugherty
jdaugherty changed the base branch from 8.0.x to 9.0.x October 30, 2026 13:39
… the provider from the beans it reaches and validate subclass instances with their own validator

The guard keyed on validation hints let a cycle of associations lead back to the instance validation
started with, or to one on the path, when it was reached with other hints, so an account validated in
a group was validated again in the default group under region.office.account. A cycle now ends at an
instance validation is cascading from, whatever hints it is reached with, as it did before: Cascade
holds the instance and the cascade it was reached through, and cascadeValidationToOne returns when the
chain leads back to the associated instance.

The traversable resolver refused the persistent associations of every bean while the GORM validator
cascades, including the beans the provider reached through a transient @Valid property, which GORM never
reaches, so their @Valid associations were validated by nobody. It refuses them on the root bean of the
provider's validation alone. The root bean is told by its path naming no property: Hibernate Validator 9
gives the root bean's own node, a nameless bean node, where earlier versions gave no node.

supports() accepts the subclasses of the entity, so a subclass instance that is an entity of its own was
validated with the rules of the superclass. validate() hands such an instance, unwrapped from a proxy, to
the validator of its own entity, with the same hints and cascade flag.

Retargeted to 9.0.x: the upgrade note moves to the Grails 9 notes and the @SInCE tags say 9.0.0.
@jdaugherty

Copy link
Copy Markdown
Contributor Author

@matrei Thanks. The PR now targets 9.0.x, and the three points are fixed in ab0a146 (the commit's diff).

Target branch

  • The base is 9.0.x. I merged 9.0.x into the branch (fdca024, clean) rather than rebasing, so the commits the reviews refer to keep their hashes.
  • The upgrade note moved to section 21 of the Grails 9 notes, reworded for Grails 9 (upgrading80x.adoc is back to the 9.0.x version), and the @since tags say 9.0.0.

1. A cycle leading back to an instance validated with hints

A cycle now ends at an instance validation is cascading from, whatever hints it is reached with. Cascade holds the instance whose associations are being cascaded to and the cascade it was reached through, so the chain on the thread is the path from the object validation started with to the current object, and cascadeValidationToOne returns when that chain leads back to the associated instance. That covers the root, your case, and any instance on the path, so a cycle behaves as on 8.0.x for a plain entity and for an annotated one. An instance reached again through another path is still validated once with each distinct set of hints, as before.

Regressions, each failing without the fix:

  • PersistentEntityValidatorSpec: a plain account whose region's office leads back to it, validated with a hint through ValidationUtils, reports owner once; and with hinting validators, an office leading back to the account and to the region it was reached through leaves both validated once, with the hints they were first reached with.
  • JakartaValidatorRegistrySpec: your example with @Valid on region and an office leading back to the account and to the region, validated in OnPublish: summary and region.code, as the provider reports, and nothing under region.office. Without hints, owner and region.name once each.
  • TCK BeanValidationSpec: the same graph as BeanValidatedAccount, BeanValidatedRegion and BeanValidatedOffice, through ValidationUtils with PublishChecks and through validate().

2. A @Valid association of a bean reached through a transient property

MappingContextTraversableResolver.isCascadable refuses a persistent association only on the root bean of the provider's validation, the instance GORM itself is validating. A bean the provider reached through a transient @Valid property cascades on through every property marked @Valid, a persistent association included, since GORM never reaches it. The root bean is told by its path naming no property: the provider gives the root bean's own node, a nameless bean node, as the path to the root bean, and the check accepts an empty path as well.

Regressions:

  • MappingContextTraversableResolverSpec: with the cascade flag off, a persistent association of the root bean is refused, whether the path is empty or the nameless bean node, and one of a bean reached through a named node is cascaded to.
  • JakartaValidatorRegistrySpec: your example reports featured.title and featured.author.name, as the provider does. The item validated on its own still reports author.name once: GORM cascades to the author, and the provider leaves it to GORM.
  • TCK BeanValidationSpec: the same with BeanValidatedHolder, BeanValidatedFeatured and BeanValidatedFeaturedAuthor, plus a save once both are valid.

The guide says that the provider validates the annotations of each value it reaches that way, not a constraints block, which it never did.

3. A subclass instance handed to the validator of its superclass

Once validate() has unwrapped the instance, an instance whose class is another entity is handed to the validator of that entity, with the same hints and the same cascade flag. supports still accepts the subclasses, so Spring's checks pass, and a proxy of a report handed to the validator of documents is validated by the validator of reports.

Regressions:

  • PersistentEntityValidatorSpec: Report extends Document with pages nullable: false and an appendix of its own: handed to the document validator with a hint, the report validator receives the hint and reports pages and appendix.label; without cascading, pages alone; a proxy of the report the same; a document is validated by the document validator itself.
  • JakartaValidatorRegistrySpec: an annotated report with a block of its own, handed to the document validator: pages (NotNull) and code (nullable), as its own validator reports them; in OnPublish, summary and code.
  • TCK BeanValidationSpec: BeanValidatedReport extends BeanValidatedDocument, handed to the document validator through ValidationUtils: pages and summary (maxSize.exceeded), the same as validate(), then a save once valid.

Docs

  • Guide: the cycle sentence, the provider's cascade from a value it reaches, and the subclass sentence.
  • Upgrade note: the same three points, in section 21 of the Grails 9 notes.

Run locally

  • Specs: PersistentEntityValidatorSpec (19), JakartaValidatorRegistrySpec (30), MappingContextTraversableResolverSpec (11), JakartaConstraintsTranslatorSpec (21) and GormValidatorAdapterSpec (9).
  • TCK BeanValidationSpec: all 23 features pass on Hibernate 5, Hibernate 7, MongoDB and Neo4j.
  • Style: codeStyle on grails-datamapping-core, grails-datamapping-validation and grails-datamapping-tck is clean.

The full module suites, the fields, OpenAPI and testing-support specs, and the docs build are left to CI this round.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fifth review of #16624 at ab0a14663e (base 9.0.x). Since my fourth review at 1bd4754bbd there are two commits: fdca024351, which merges the 9.0.x tip d8016801588, and ab0a14663e. The merge commit has the same tree as the merge git produces on its own, so nothing was resolved by hand. The branch is up to date with 9.0.x, and git merge-tree against it is clean. I reviewed ab0a14663e.

What I ran and checked:

  • Tests at the head, all green:
    • :grails-datamapping-validation:test: 70 tests.
    • :grails-datamapping-core:test: 2734 tests.
    • :grails-testing-support-datamapping:test: 10 tests.
    • :grails-fields:test: 699 tests, and :grails-openapi:test: 305 tests.
    • The TCK BeanValidationSpec, all 23 features, on Hibernate 5, Hibernate 7, MongoDB and Neo4j, with the grails.gorm.tests.validation specs on both Hibernate versions.
    • :grails-datamapping-core-test:test: 714 tests, with BeanValidationSpec skipped as intended.
    • TicketValidationSpec and TicketControllerSpec in both grails-hibernate test apps: 10 tests each.
  • Style: codeStyle is clean on grails-datamapping-core, grails-datamapping-validation, grails-datamapping-tck, grails-testing-support-datamapping, grails-fields and grails-openapi.
  • Docs: :grails-doc:publishGuide -x aggregateGroovydoc builds without warnings. Section 21 renders, and its validation.html#beanValidation link and the guide's #constraints links resolve.
  • Probe specs, not committed: run at this head and on the 9.0.x tip, each case compared with what a plain Hibernate Validator reports for the same instances.
  • CI: 75 checks had passed and 14 were still pending when I checked. One failed: Hibernate7 Functional Tests (Java 21, indy=false, shard 2), with an OutOfMemoryError in the Hibernate 7 test JVM after 4386 tests and no test failures. The Hibernate 7 functional tests fail the same way on the last two pushes to 9.0.x, including d8016801588, which this branch merges, so I don't think the failure comes from this PR. No check builds the guide.

The retarget is done, and all three points of my fourth review are fixed, each with regression tests. One bug is left in the cascade (1). It isn't new, so a follow-up would be fine, but this PR is a natural place to fix it. The rest is small.

The fourth review's findings

# Probe 9.0.x tip this head
1 Plain A → B → C → A with name nullable: false on A, validated with a hint name name
1 Your annotated account in OnPublish, with the office leading back to it summary summary, as Hibernate Validator reports
1 An instance in the middle of the path, converted to another group, reached again through a cycle of plain associations nothing b.x, as Hibernate Validator reports
2 Your Holder, Featured and Author nothing featured.title and featured.author.name, as Hibernate Validator reports, with deepValidate: false too
3 A plain report with pages nullable: false, handed to the validator of plain documents IllegalArgumentException pages, as its own validator reports
3 An annotated report with a block of its own, handed to the validator of annotated documents, with and without OnPublish the annotations only the annotations and the block, as its own validator reports

1. The cascade validates a subclass instance with the rules of the declared type

validate() now hands an instance of a subclass entity to that entity's validator (PersistentEntityValidator.groovy:138). The cascade doesn't. cascadeValidationToOne takes the entity, the reflector and the validator from the declared type of the association (:463, :474, :479). So when an association declared as a superclass holds an instance of a subclass entity, the subclass's own rules are checked only in part, or not at all:

@Entity
class Document {
    @NotBlank String title
}

@Entity
class Report extends Document {
    @NotNull Integer pages
    String extra
    static constraints = { extra nullable: false }
}

@Entity
class Folder {
    @NotNull String name
    @Valid Document doc
}

def folder = new Folder(name: 'f', doc: new Report(title: 'ok', pages: null, extra: null))
// folder.validate():     doc.pages (NotNull)
// folder.doc.validate(): pages (NotNull), extra (nullable)
// Hibernate Validator:   doc.pages (NotNull)

Three combinations:

  • Annotated superclass, as above: the document validator runs Bean Validation, which reads the runtime class, so doc.pages is reported. The report's block isn't checked, so extra is missing.
  • Plain superclass and plain subclass, where the report's only rule is pages nullable: false: nothing is reported through the folder, while the report's own validator reports pages.
  • Plain superclass, annotated subclass (@NotNull Integer pages): nothing is reported through the folder either. The report's own validator is a JakartaPersistentEntityValidator, but the cascade uses the plain document validator.

It isn't a regression: 9.0.x reports nothing through the folder in all three. I still think it's a bug, one GORM's cascade has always had, rather than a choice:

  • The rules of an instance belong to its class.

    • report.validate() and report.save() apply the report's rules.
    • Hibernate Validator validates the runtime class.
    • The handoff in validate() now does the same.

    The cascade is the only path that validates a report as a document. In the first combination it even mixes the two: the report's annotations with the document's block.

  • The schema doesn't catch what the cascade skips. With table per hierarchy, the default, the binder makes every column of a subclass nullable, whatever its block says (Hibernate 5: GrailsDomainBinder.java:2247-2256 and :3149-3156). So a subclass's nullable: false is enforced by validation alone.

  • The guide says otherwise. It says the cascade validates "the annotations of an annotated associated class together with its constraints block" (beanValidation.adoc:49).

cascadeValidationToOne could take the entity from the class of the instance, the way findSubclassEntityValidator (:165) does. That changes what a plain domain class reports through such an association, so it needs a line in the upgrade note. That's fine now that the PR targets 9.0.x. This PR is a natural place for the fix, since it adds the same lookup to validate(). If you'd rather do it in a follow-up, please open an issue for it and narrow the guide sentence to say that the declared type of the association decides.

2. Smaller points

  • PR description: it still says the change is documented "in the 8.0.x upgrade notes", and it still offers to move the PR to 9.0. If the squash commit takes the description, it's worth updating. A squash merge also keeps fdca024351 out of 9.0.x.
  • Javadoc line (nit): JakartaPersistentEntityValidator.groovy:179 is 200 characters long. The rest of that paragraph wraps at 120.
  • The null fix on 8.0.x: your reply doesn't mention it. Do you plan to send the MappingContextTraversableResolver null fix to 8.0.x on its own? It isn't needed for this PR.

Verified as correct

  • Retarget:
    • upgrading80x.adoc is identical to 9.0.x.
    • The note is section 21 of upgrading90x.adoc, after 20, and it compares Grails 9 with Grails 8.
    • No 8.0.1 is left: the @since tags say 9.0.0.
    • The new files have the license header and no @author.
  • Cycles (my fourth review's 1):
    • Cascade now holds the instance and the cascade it was reached through, so leadsBackTo walks the path from the instance validation started with to the current one.
    • validate() starts a chain without a parent, so a validation run by a custom constraint has a path of its own, and the enclosing chain is restored in a finally.
    • The check comes before the hints are computed and before the visited set (PersistentEntityValidator.groovy:442). So an instance reached again through another path is still validated once for each distinct set of hints.
    • One case differs from Hibernate Validator, and the guide states the rule. A root with @Valid @ConvertGroup(from = Default, to = X) mid, a mid converting X to Y for its leaf, and a leaf with @Valid root. Hibernate Validator validates the root again in Y and reports mid.leaf.root.ycheck. GORM ends the cycle at the root. I'd keep it that way: GORM cascades through every association, not only @Valid ones, and keying the cycle on the groups is what caused 1 in my fourth review.
  • Transient @Valid values (my fourth review's 2):
    • isRootBean (MappingContextTraversableResolver.groovy:119) treats an empty path, or one of nameless bean nodes, as the root, and any named or non-bean node as a cascaded bean.
    • So persistent associations are refused only on the bean GORM itself validates. That includes an associated instance whose annotations validateBeyondConstraints validates, which GORM cascades from itself.
    • Uninitialized proxies and lazy collections are still unreachable through isReachable, which is unchanged.
  • Subclass handoff (my fourth review's 3):
    • The handoff comes after the unwrap, so a proxy of a report reaches the report validator.
    • The targetClass of that validator is the class of the instance, so it doesn't hand off again.
    • A subclass that isn't an entity stays with the validator it was handed to.
    • The hints are passed on: in OnPublish, the annotated report gets summary (NotBlank) and extra (nullable), as from its own validator.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nested cascade flags, scalar runtime conversions, and per-instance default sequences are fixed. A set element, a subclass held in a superclass association, and a group sequence still drop or repeat violations.

…the element of a set the provider cascaded to and validate a group of a sequence once

The cascade took the entity, the reflector and the validator from the declared type of an association,
so an instance of a subclass entity held by an association declared as the superclass was validated
with the rules of the superclass: its own constraints block, annotations and associations went
unchecked through the association, while validate() handed such an instance to the validator of its
own entity. cascadeValidationToOne now resolves the entity of the class of the instance, as validate()
does, and validates it with the constraints, the associations and the validator of that entity.

The adapter read the beans the provider cascaded to from the validated object, following the index or
key of the next node of the path, which an element of a set has none of, so the element was taken for
the declared type of the property and a @ConvertGroup of its class was dropped. It now reads the value
Hibernate Validator records on the node of a cascaded property, the bean it cascaded to, and walks from
the validated object only for a provider recording none.

Hints naming a group both on its own and in a group sequence validated the group twice, so one failing
annotation became two field errors where the provider reports it once, and the duplicate stopped the
sequence. A group of a sequence validated already in the same validation is skipped, and the groups a
group extends that were validated already are left out of its step through the excluded groups. The
violations of the constraints block, validated before the groups, were part of the baseline a sequence
stops against, so a failing block on the validated object let every group run: the hook receives the
error count before the block and counts its violations as violations of the first group the object is
validated in, as it does for an associated object reached in a group.
The Hibernate 7 core suite runs out of its default test fork heap on 9.0.x, and sits a few megabytes
under it on 8.x: a heap dump at the OOM shows java.beans.ThreadGroupContext, the JDK Introspector's
BeanInfo cache, retaining 203 MB, 41% of the heap, for 6,700 classes, with 370,000 method
descriptors. Groovy reads the BeanInfo of a class when it builds its MetaClass, and the cache is keyed
by the class and releases an entry only when the class is unloaded, which never happens in a test JVM.
The domain classes of the TCK and of each spec cost about 330 method descriptors each, and every
closure of every spec is a class with an entry of its own. The suite grew past the heap when the
merge-up of 2026-10-30 added specs, and a pull request adding domain classes to the TCK tips it over.

GrailsDataTckManager.cleanupSpec() now flushes the Introspector's caches, as cleanRegistry() already
removes the MetaClasses of the domain classes. The suite's live set stops growing with the number of
specs that have run; a class a later spec builds a MetaClass for is introspected again. With the flush
the suite passes at the default heap in 7 minutes where it took 11 with a full GC every few tests, or
failed.

(cherry picked from commit 46d0b25)

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Round at af5d40a, for the reviews at ab0a146 (matrei's fifth, jamesfredley's three threads). An eighth commit, as before.

  • The cascade validated a subclass instance with the rules of the declared type (matrei 1, thread on cascadeValidationToOne). cascadeValidationToOne resolves the entity of the class of the associated instance, as validate() does for the object it starts with, and takes the constraints, the reflector and the validator from it, so a report held by an association declared as a document is validated with the report's block, annotations and associations. Regressions: PersistentEntityValidatorSpec (a plain folder whose document is a plain report: document.pages and document.appendix.label, by the validator of reports), JakartaValidatorRegistrySpec (your three combinations: an annotated report through @Valid, in the default group and in OnPublish, with its block, checked against Hibernate Validator; an annotated memo held by a plain folder as a plain document) and the TCK BeanValidationSpec (BeanValidatedFolder holding a BeanValidatedReport). The guide says the class of the instance decides, and the upgrade note has a bullet, as it changes what a plain domain class reports through such an association.
  • An element of a transient @Valid set was taken for its declared type (thread on cascadedBeanOf). The adapter reads the value Hibernate Validator records on the node of a cascaded property, the bean it cascaded to (org.hibernate.validator.path.PropertyNode.getValue()), an element of a set included, and walks from the validated object only for a provider recording none. Regressions: GormValidatorAdapterSpec (Stamp.attachments, a Set<Object> whose elements convert ExtendedGroup to DetailGroup for their details) and JakartaValidatorRegistrySpec (your case: ExtendedChild.records, validated in Extended, reports child.records[].details.summary and not the Base violation, as the provider does).
  • A group given on its own and in a sequence was validated twice, and a failing block did not stop a sequence (thread on validateAssociationsAndBeyond). A group of a sequence that this validation validated already, on its own or in an earlier sequence, is skipped, as the provider adds no violation for a constraint it processed, and the groups a group extends that were validated already are left out of its step through ExcludedGroups. With [StepA, StepAThenB] a root failing StepA is reported once, and the sequence, which the group validated on its own does not stop, goes on to StepB, as Hibernate Validator does. The hook receives the error count before the constraints block, and the block's violations count as violations of the first group the object is validated in, as they do for an associated object reached in a group: with [StepAThenB] alone, a failing block stops the sequence after StepA; with StepA given on its own as well, the block belongs to the groups validated on their own, which stop no sequence. Regressions: JakartaValidatorRegistrySpec (both, checked against Hibernate Validator where it has a say) and the TCK BeanValidationSpec (BeanValidatedBrief in PublishThenArchive).
  • Docs and the PR (matrei 2). The javadoc line is wrapped at 120, and the description says the Grails 9 upgrade notes and no longer offers to move the PR.

Run locally: PersistentEntityValidatorSpec, JakartaValidatorRegistrySpec, GormValidatorAdapterSpec, JakartaConstraintsTranslatorSpec and MappingContextTraversableResolverSpec; the TCK BeanValidationSpec, 25 features, on Hibernate 5, Hibernate 7, MongoDB and Neo4j (Docker), with the grails.gorm.tests.validation specs of both Hibernate versions; codeStyle on grails-datamapping-core, grails-datamapping-validation and grails-datamapping-tck. The six new features fail without the changes.

…dation-constraints

# Conflicts:
#	grails-data-hibernate5/core/src/test/groovy/org/apache/grails/data/testing/tck/base/GrailsDataTckManagerSpec.groovy
#	grails-datamapping-tck/src/main/groovy/org/apache/grails/data/testing/tck/base/GrailsDataTckManager.groovy

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A set element keeps its converted group, a subclass in a superclass association uses its own validator, and a group that this pass already ran is not run again. Not approving. A basic collection such as a set of enums is cascaded by neither validator, so an invalid element is accepted. Cascaded constraints are also chosen before beforeValidate, so a group-sequence provider that changes during that callback is checked against the old state.

… the rules of an associated instance after its beforeValidate callback

The traversable resolver refused every persistent association of the root bean while the GORM
validator cascades, a basic collection included. The GORM validator has nothing to validate the
elements of a basic collection with, as it has no associated entity, so cascadeValidationToOne
returned at once and an element with a failing constraint, such as an enum whose @AssertTrue getter
returns false in a @Valid Set, was accepted by both validators. The resolver now refuses only the
associations with an associated entity, the ones the GORM validator cascades to, so the provider
cascades to the elements of a basic collection as it does to a transient @Valid property.

The cascade chose the constraints of an associated instance, with getValidatedConstrainedProperties,
before it invoked its beforeValidate callback. For an entity whose rules depend on its state, such as
one with a @GroupSequenceProvider, the nullability constraints of the block were relaxed for the
sequence of the state before the callback while the provider validated the state after it, so a
violation passed that validation and failed the next one. The callback is invoked first, with the
names of the constrained properties the validator exposes, as on 9.0.x, and the constraints are
chosen once it has run.

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Round at 9c4d611, for the review at d65a45c (two threads). A ninth commit, as before.

  • An element of a basic collection marked @Valid was validated by neither validator (thread on MappingContextTraversableResolver). While the GORM validator cascades, the resolver refuses on the root bean only an association with an associated entity, the ones the GORM validator has a validator for. A basic collection has none, so the provider cascades to its elements, as it does to a transient @Valid property: with or without deepValidate, and in the groups of the instance owning it. Regressions: MappingContextTraversableResolverSpec (a basic collection of the root bean is cascadable), JakartaValidatorRegistrySpec (your case, a @Valid Set of enums holding one whose @AssertTrue getter fails: statuses[].supported on its own and without cascade, tasks[0].statuses[].supported through an owner) and the TCK BeanValidationSpec (BeanValidatedTask).
  • The constraints of a cascaded child were chosen before its beforeValidate (thread on cascadeValidationToOne). The callback is invoked first and the constraints are chosen after it, so the block gives way to the annotations of the sequence the provider chooses for the state the callback leaves, the state Bean Validation then validates. The callback still receives the names of the constrained properties the validator exposes, as on 9.0.x. Regressions: PersistentEntityValidatorSpec (a validator recording the state it chooses the constraints for, and the names the callback is given), JakartaValidatorRegistrySpec (your case, a member retired until its callback and without a desk: member.desk is nullable on the first validation and on the next) and the TCK (BeanValidatedRoster holding a BeanValidatedReturnee).

The four unit features fail without the change, and so do the two TCK features (checked on Hibernate 5). The TCK spec passes on Hibernate 5, Hibernate 7, MongoDB and Neo4j. The TCK task is validated and not saved, as GORM for Neo4j does not persist a collection of enums. The guide and the upgrade note cover both points.

Both failed on Windows CI runs of pull requests that do not touch the module.

The tasks feature signed its browser in with one request while the application
was free to hand the port from the progress server to the web server, so a
sign-in arriving during the hand-off got no answer. startSignedIn now holds the
beans until the browser has signed in, as the other features already do, and a
sign-in that gets no answer fails with the reason and the application's log
rather than with a null response.

The failed-start feature polled as a second page after the first had been told,
which is only answered for the 750 ms the port is held. A runner that stalls the
spec for longer has polled too late to tell, so that poll now counts only when
it was made within the page's polling interval of the first.

A feature given a port an earlier feature had also inherited the file recording
the browser opened on it; setup now removes it.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A basic collection is cascaded, and beforeValidate runs before the cascaded constraints are chosen. Not approving. In a unit test, a constraint validator that needs an injected service is created without that service, so a value the running application accepts is rejected.

"${BEAN_NAME}"(constraintsEvaluator, constraintRegistry, grailsDomainClassMappingContext,
ConstraintEvalUtils.getDefaultConstraints(application.config), true, ConstraintEvalUtils.getDefaultNullable(application.config))
if (JakartaValidatorRegistry.isAvailable()) {
"${VALIDATOR_FACTORY_BEAN_NAME}"(JakartaValidatorRegistry, grailsDomainClassMappingContext, ref('messageSource')) { bean ->

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A unit test whose custom constraint validator autowires a service rejects the value OK when that service accepts it. The factory is given a StaticMessageSource, so Spring never injects the validator. Pass the test application context. Keep annotation validation in the unit test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Verified at cbcea53ef1b0: the unit-test validator factory receives the test application context, so custom constraint validators receive their injected services while annotation validation remains enabled. The DataTest injection regression passes. Upstream EL fix #17175 is now in the merged base, and the four existing EL-bounds regressions pass too; this PR adds no separate EL implementation change.

Build the Bean Validation factory with the DataTest application context so custom constraint validators receive their Spring dependencies. Cover acceptance, rejection and save through the public domain API.
@testlens-app

testlens-app Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🚨 TestLens detected 2 failed tests 🚨

Test Summary

Tip

Inspect all details with the TestLens CLI: testlens pr 16624

CI / Build Grails-Core (Windows JDK 25 shard 2) > :grails-startup-progress:test

Test Runs Flakiness
StartupProgressSpec > tells a watching page why the start failed while #stage, then releases the port > tells a watching page why the start failed while starting the web server, then releases the port ❌ 0% 🟢

CI / Functional Tests (Java 21, indy=false) > :grails-test-examples-issue-11102:integrationTest

Test Runs Flakiness
FailedActionObservationSpec > a failed action is reported once with its own exception when its error controller fails with a server error Spring MVC resolves, asynchronously ❌ 0% 🟢

🏷️ Commit: cbcea53
▶️ Tests: 174465 executed
⚪️ Checks: 101/101 completed

Test Failures

StartupProgressSpec > tells a watching page why the start failed while #stage, then releases the port > tells a watching page why the start failed while starting the web server, then releases the port (:grails-startup-progress:test in CI / Build Grails-Core (Windows JDK 25 shard 2))
java.lang.AssertionError: No FAILED status within 30 seconds
	at org.apache.grails.startup.StartupProgressSpec.awaitStatus(StartupProgressSpec.groovy:1057)
	at org.apache.grails.startup.StartupProgressSpec.tells a watching page why the start failed while #stage, then releases the port(StartupProgressSpec.groovy:327)
FailedActionObservationSpec > a failed action is reported once with its own exception when its error controller fails with a server error Spring MVC resolves, asynchronously (:grails-test-examples-issue-11102:integrationTest in CI / Functional Tests (Java 21, indy=false))
org.spockframework.runtime.extension.builtin.PendingFeatureSuccessfulError: Feature is marked with @PendingFeature but passes unexpectedly
	at org.spockframework.runtime.extension.builtin.PendingFeatureBaseInterceptor.featurePassedUnexpectedly(PendingFeatureBaseInterceptor.java:28)
	at org.spockframework.runtime.extension.builtin.PendingFeatureInterceptor.intercept(PendingFeatureInterceptor.java:30)
	at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:139)
	at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:157)
	at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:157)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
	at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:157)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

Rerun Controls

Select tests to mute in this pull request:

  • FailedActionObservationSpec > a failed action is reported once with its own exception when its error controller fails with a server error Spring MVC resolves, asynchronously
  • StartupProgressSpec > tells a watching page why the start failed while #stage, then releases the port

Reuse successful test results:

  • ♻️ Only rerun the tests that failed or were muted before

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

This branch has not been deployed

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

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

3 participants