Repository navigation
Validate the constraints block of Bean Validation annotated domain classes and expose their constraints - #16624
jdaugherty wants to merge 15 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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 🚀 New features to boost your workflow:
|
2894f42 to
2803750
Compare
matrei
left a comment
There was a problem hiding this comment.
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: withDataTestand with a real Hibernate 5HibernateDatastore. They cover cascading into associations, a group-restricted annotation, a cross-field@AssertTrue, a class-level constraint, and a null@NotBlanksaved withflush: 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 checkedPersistentEntityValidator.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
@Validis 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.
SpringValidatorAdapteralready prefixes field errors with the nested path of theErrors.
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 == falsefindNullabilityConstrainedProperties (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@NotBlankproperty passesvalidate(). Hibernate's own persist-time Bean Validation then throwsjakarta.validation.ConstraintViolationException(save(flush: true)on Hibernate 5). nullable,uniqueandmaxSizein 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:matchesinListminandmaxemail- 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
BeanValidationSpecadditions are nearly the same. MongoDB gets the sameJakartaValidatorRegistrythroughValidatorRegistriesbut has no test. One TCK spec ingrails-datamapping-tckwould 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 inconstrainedPropertiesas a propertyrangeValidwithinList: [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.entityConstraintsingrails-openapinow gets constraints for annotated domain classes, where it used to get an empty map. The generated schema for those classes changes (requiredlists, 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)returnsfalse, which is why@NotNullnever fired there.GroovyProxyFactoryandJavassistProxyFactoryalready treated null as initialised. - The new
isReachablereads the value throughClassPropertyFetcher, as the handlers'isInitialized(obj, name)did. So an uninitialised proxy or a lazy collection is still unreachable.
- On Hibernate 5 and 7,
- 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
@NotNullandnullable: falseon the same property, a null is reported once, asNotNull.
- It changes only the validator's own constraints, which come from a fresh
- Unannotated properties: with the Grails 8 default
nullable: true, they stay optional, so validating the block doesn't suddenly make them required. uniquesurvives the copy into the exposed constraints:- Hibernate 5, Hibernate 7 and MongoDB add
UniqueConstraintto the registry thatcreateEntityValidatorbuilds with. DataTestadds it to theconstraintRegistrybean it passes in.
- Hibernate 5, Hibernate 7 and MongoDB add
DataTestwiring:grails-datamapping-corehashibernate-validatoras animplementationdependency, so Jakarta Validation is on the runtime classpath. The new checks inDataTestandDataTestSetupSpecInterceptorcan't hit a missing class. The newtestImplementationis 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.ymlentry, thevalidation.html#beanValidationandtesting.html#unitTestingDomainClassesanchors, and the upgrade-note number (87, after 86).
jamesfredley
left a comment
There was a problem hiding this comment.
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.
2803750 to
d4f19e4
Compare
|
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
Run locally: @jamesfredley on the fields plugin ( Addressed by the design change rather than an edit to The three inline threads have their own replies. |
jamesfredley
left a comment
There was a problem hiding this comment.
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.
d4f19e4 to
74cebef
Compare
74cebef to
d3f8ba5
Compare
matrei
left a comment
There was a problem hiding this comment.
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
BeanValidationSpecran all 7 features on Hibernate 5, Hibernate 7, MongoDB and Neo4j. :grails-datamapping-core-test:test, the simple-datastore TCK suite: 687 tests. The 7BeanValidationSpecfeatures are skipped there, as intended.
- Style:
codeStyleon the six changed modules is clean. - Probe specs from my first review, not committed, run again at this head with
DataTestand with a real Hibernate 5HibernateDatastore. I added three cases: a class-level constraint on an associated domain class,@Validon an association to an annotated class, and ahasOneto an annotated class. - CI: the PR has the
no cilabel, so no workflow ran ond4f19e4a3f,74cebef5fcor 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
@Validon the association, the child's annotation error is reported once. - A
hasOneto an annotated class reportsdetail.label(NotBlank) anddetail.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]') // falseThe 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:hasErrorsandgetFieldError('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 aGormValidatorAdapteralone. MongoDB and Neo4j have no schema, so for themnullableandmaxSizefrom the block are enforced for the first time as well. - The same holds for the
nullable: falsethatgrails.gorm.default.nullable = falsegives every unannotated property. On those datastores, every such property of an annotated class now becomes required invalidate(). - 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].labelandNotBlank.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.labelapplies when the line is validated on its own, but not through the invoice.NotBlank.lines.label,NotBlank.labelandNotBlankwork both ways. - Spring's nested validation names them the same way, so a sentence in the guide is enough.
- The class-qualified codes of a cascaded Bean Validation error name the validated class and the path:
no cilabel: please remove it before merge so the final head gets a full CI run.
Verified as correct
- Validator split:
JakartaValidatorRegistryregisters aJakartaPersistentEntityValidatorfor an entity carrying@Validated, and the plainPersistentEntityValidatorfor every other entity.- For a plain entity,
getValidatedConstrainedProperties()returns the same map as before andvalidateBeyondConstraintsdoes nothing. So validation of unannotated domain classes is unchanged. - The consumers that check for a
PersistentEntityValidator:- the cascade itself;
DomainPropertyImplin grails-fields;PersistentGraphQLProperty, which reads onlyorderfrom 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
validatedObjectsguard, and never cascades on its own (validate(obj, errors, false)). deepValidate: falseskips the associated objects.
- Groups:
- The translator reads the
BeanDescriptorand 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
BeanValidatedArticlecase covers that on all four datastores.
- The translator reads the
- Composed constraints: they are described from the provider's descriptors, so an
@OverridesAttributeis 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). OpenApiFixturenow 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.
- The TCK spec replaces the Hibernate 5 and Hibernate 7 copies. It is skipped in the simple-datastore suite through
- Docs:
link:validation.html#constraintsresolves to the Declaring Constraints section.- The upgrade note is number 89, after 88 on the current
8.0.xtip.
d3f8ba5 to
cbfe65b
Compare
cbfe65b to
051efbe
Compare
|
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 classThe fix is in
The adapter now overrides
Regressions:
Both fail without the adapter change. 2. Smaller points
|
jamesfredley
left a comment
There was a problem hiding this comment.
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.
|
@jamesfredley Thanks. All three are fixed in 491fca0 (diff against 051efbe12c). 1.
|
…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.
41c275b to
491fca0
Compare
…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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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, asvalidate()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 TCKBeanValidationSpec(BeanValidatedShelfBook.proxy(id), initialized after asession.clear(), as the book of a shelf). All fail without the fix, the TCK one on Hibernate 5 with aHibernateProxy. - A converted group on a transient
@Validchild was dropped (thread on the adapter).GormValidatorAdapterdecides 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@ConvertGroupannotations of each property the provider cascaded through declare, the wayvalidateCascadedAnnotatedObjectForCurrentGroupconverts 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,ExtendedChildwith transient details convertingExtendedtoDetailsChecks: validated inExtended, the owner reportschild.details.summaryand not theBaseviolation of the details, and nothing inBase, both as Hibernate Validator does) andGormValidatorAdapterSpec(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). Eachvalidateoverload now remembers the value ofCASCADE_VALIDATIONit found and puts it back when it ends, removing it only when there was none, so a custom constraint validating another domain instance withvalidate()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.labelis still reported) and the TCKBeanValidationSpec(BeanValidatedLedger, whose@ValidCounterpartcallscounterpart.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 anObject, convertingExtendedGrouptoDetailGroupfor its details) andJakartaValidatorRegistrySpec(your case:ExtendedChild.record, anObjectholding a record that convertsExtendedtoDetailsChecksfor its details; validated inExtended, the owner reportschild.record.details.summary, as the provider does). - A
@GroupSequenceProviderwas frozen to the static annotations (thread ongetValidatedConstrainedProperties).JakartaConstraintsTranslatortreats a class with the provider as redefining the default group, asvalidateConstraintsForDefaultGroupdoes: the class is described with the sequence the provider gives for no instance, as itsBeanDescriptoris, andfindDefaultGroups(instance)gives the groups of the sequence the provider chooses for an instance.PersistentEntityValidator.getValidatedConstrainedPropertiesnow receives the object, soJakartaPersistentEntityValidatorrelaxes thenullableconstraints 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 ofProvidedProduct),JakartaValidatorRegistrySpecand the TCKBeanValidationSpec(your case,nullable: falsewith@Null(groups = RetiredChecks): an active member without a desk getsnullable, a retired one is valid, as the provider says, and a retired one with a desk getsNull; theconstrainedPropertiesdescribe the class for no instance, sodeskstays 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
left a comment
There was a problem hiding this comment.
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 thegrails.gorm.tests.validationspecs on both Hibernate versions. :grails-datamapping-core-test:test: 700 tests, withBeanValidationSpecskipped as intended.TicketValidationSpecandTicketControllerSpecin bothgrails-hibernatetest apps: 10 tests each.
- Style:
codeStyleis clean ongrails-datamapping-core,grails-datamapping-validation,grails-datamapping-tckandgrails-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
constraintsblock 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; @ConvertGroupand group sequences across GORM's cascade, and@GroupSequenceProvider;- the annotations described in
constrainedPropertiesfor scaffolding, the fields plugin and OpenAPI; - new protected hooks on
PersistentEntityValidator.
- validation groups through
- 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.xalready containse4b22127dc, andgit merge-treeagainst it is clean, so changing the base branch should be enough.- The upgrade note would move to
upgrading90x.adoc, and the@since 8.0.1tags would become9.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 asValidatedObject(target, hints)(PersistentEntityValidator.groovy:135).cascadeValidationToOnekeys 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: neitherIt 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 itsauthor.
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 reportspages(nullable).- 8.0.x threw an
IllegalArgumentExceptionbecause 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:
ValidatedObjectandValidatedConstraintsuseis()andSystem.identityHashCode. The basket case now reportslines[1].code, as on 8.0.x. -
isBeanValidatedasks 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 @ConvertGroupassociation convertsDefaultall report what Hibernate Validator reports.getValidatorcaches the decision,DataTestasks 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/Grandchildcase reportschild.grandchild.xalone, andchild.bonce the grandchild is valid, as Hibernate Validator does. This matchesvalidateInContext:- 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
constraintsblock 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
SmartValidatorparagraph showsgetEntityValidator, the upgrade note's bullet is split up, and the two test apps use theorg.apache.grailscoordinates.
-
- James's threads: I read the fixes and their regression tests, which check Hibernate Validator's result first.
- Proxies are unwrapped in
validate()and incascadeValidationToOne, while an uninitialized to-one proxy is still skipped bycascadeToAssociativeProperty. - The provider cascades through a transient
@Validproperty. - The excluded groups of an extended group are left out.
ORcompositions aren't described.- All three overloads of the adapter restore the cascade flag.
isReportedfollows the runtime beans.@GroupSequenceProvideris supported.
- Proxies are unwrapped in
- Plain entities otherwise behave as before:
- Splitting
validate()intovalidateConstraintsandvalidateAssociationsAndBeyondkeeps the order of the errors: an owner'sname, thenitems[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.
beforeValidateruns once for each associated instance.
- Splitting
…dation-constraints
… 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.
|
@matrei Thanks. The PR now targets Target branch
1. A cycle leading back to an instance validated with hintsA cycle now ends at an instance validation is cascading from, whatever hints it is reached with. Regressions, each failing without the fix:
2. A
|
matrei
left a comment
There was a problem hiding this comment.
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 thegrails.gorm.tests.validationspecs on both Hibernate versions. :grails-datamapping-core-test:test: 714 tests, withBeanValidationSpecskipped as intended.TicketValidationSpecandTicketControllerSpecin bothgrails-hibernatetest apps: 10 tests each.
- Style:
codeStyleis clean ongrails-datamapping-core,grails-datamapping-validation,grails-datamapping-tck,grails-testing-support-datamapping,grails-fieldsandgrails-openapi. - Docs:
:grails-doc:publishGuide -x aggregateGroovydocbuilds without warnings. Section 21 renders, and itsvalidation.html#beanValidationlink and the guide's#constraintslinks resolve. - Probe specs, not committed: run at this head and on the
9.0.xtip, 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 anOutOfMemoryErrorin 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 to9.0.x, includingd8016801588, 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.pagesis reported. The report's block isn't checked, soextrais 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 reportspages. - Plain superclass, annotated subclass (
@NotNull Integer pages): nothing is reported through the folder either. The report's own validator is aJakartaPersistentEntityValidator, 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()andreport.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-2256and:3149-3156). So a subclass'snullable: falseis enforced by validation alone. -
The guide says otherwise. It says the cascade validates "the annotations of an annotated associated class together with its
constraintsblock" (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
fdca024351out of9.0.x. - Javadoc line (nit):
JakartaPersistentEntityValidator.groovy:179is 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 theMappingContextTraversableResolvernull fix to8.0.xon its own? It isn't needed for this PR.
Verified as correct
- Retarget:
upgrading80x.adocis identical to9.0.x.- The note is section 21 of
upgrading90x.adoc, after 20, and it compares Grails 9 with Grails 8. - No
8.0.1is left: the@sincetags say9.0.0. - The new files have the license header and no
@author.
- Cycles (my fourth review's 1):
Cascadenow holds the instance and the cascade it was reached through, soleadsBackTowalks 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 afinally.- 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 convertingXtoYfor its leaf, and a leaf with@Valid root. Hibernate Validator validates the root again inYand reportsmid.leaf.root.ycheck. GORM ends the cycle at the root. I'd keep it that way: GORM cascades through every association, not only@Validones, and keying the cycle on the groups is what caused 1 in my fourth review.
- Transient
@Validvalues (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
validateBeyondConstraintsvalidates, 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
targetClassof 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 getssummary(NotBlank) andextra(nullable), as from its own validator.
jamesfredley
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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).cascadeValidationToOneresolves the entity of the class of the associated instance, asvalidate()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.pagesanddocument.appendix.label, by the validator of reports),JakartaValidatorRegistrySpec(your three combinations: an annotated report through@Valid, in the default group and inOnPublish, with its block, checked against Hibernate Validator; an annotated memo held by a plain folder as a plain document) and the TCKBeanValidationSpec(BeanValidatedFolderholding aBeanValidatedReport). 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
@Validset was taken for its declared type (thread oncascadedBeanOf). 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, aSet<Object>whose elements convertExtendedGrouptoDetailGroupfor their details) andJakartaValidatorRegistrySpec(your case:ExtendedChild.records, validated inExtended, reportschild.records[].details.summaryand not theBaseviolation, 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 throughExcludedGroups. With[StepA, StepAThenB]a root failingStepAis reported once, and the sequence, which the group validated on its own does not stop, goes on toStepB, 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 afterStepA; withStepAgiven 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 TCKBeanValidationSpec(BeanValidatedBriefinPublishThenArchive). - 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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Round at 9c4d611, for the review at d65a45c (two threads). A ninth commit, as before.
- An element of a basic collection marked
@Validwas validated by neither validator (thread onMappingContextTraversableResolver). 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@Validproperty: with or withoutdeepValidate, 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 Setof enums holding one whose@AssertTruegetter fails:statuses[].supportedon its own and without cascade,tasks[0].statuses[].supportedthrough an owner) and the TCKBeanValidationSpec(BeanValidatedTask). - The constraints of a cascaded child were chosen before its
beforeValidate(thread oncascadeValidationToOne). 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 on9.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.deskisnullableon the first validation and on the next) and the TCK (BeanValidatedRosterholding aBeanValidatedReturnee).
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
left a comment
There was a problem hiding this comment.
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 -> |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 detected 2 failed tests 🚨Test SummaryTip Inspect all details with the TestLens CLI: CI / Build Grails-Core (Windows JDK 25 shard 2) > :grails-startup-progress:test
CI / Functional Tests (Java 21, indy=false) > :grails-test-examples-issue-11102:integrationTest
🏷️ Commit: cbcea53 Test FailuresStartupProgressSpec > 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))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))Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
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 aPersistentEntityValidator, soconstrainedPropertieswas empty for scaffolding and plugins, and validation cascading into such a class checked nothing), null values were never reached by@NotNulland friends because the traversable resolver treated a null property as uninitialized, and the unit test datastore ignored the annotations altogether.JakartaValidatorRegistrynow registers aJakartaPersistentEntityValidatorfor an annotated entity: aPersistentEntityValidatorthat 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@Validproperty that is not an association between entities, such as a transient property or a basic collection.PersistentEntityValidatorgains thevalidateBeyondConstraintshook 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, asvalidate()hands such an instance to the validator of its own entity. ThebeforeValidatecallback 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@Validis thus validated in the groups of its owner, converted as@ConvertGroupdeclares, 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.PersistentEntityValidatoris aSmartValidator, as the adapter it replaces was: the validation hints Spring'sDataBinderandValidationUtilspass are the groups an annotated entity is validated in, and it cascades with them. The GORMnullableconstraint 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@GroupSequenceapplies the sequence to its own constraints and to the ones of its superclasses, while the classes below it validate theirs in theDefaultgroup. 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 aPersistentEntityValidator, such as the fields plugin, the GraphQL properties and the OpenAPI descriptions, sees the merged constraints without a change.MappingContextTraversableResolvertreats a null value as reachable.DataTestcreates the same validator for annotated domain classes. The Hibernate 5 and 7 specs are replaced by one TCK spec that runs on every datastore. Thegrails-hibernatetest 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 isfc1b021c3e5af566d8c77756808b79b17b2c531e: