Repository navigation
Conversation
A multi-tenant entity's tenant id is mapped as a derived property, and DefaultConstraintEvaluator dropped the constraints of derived properties with a warning, so a tenant id declared nullable: false, or with a maxSize, was never validated. Hibernate then rejected the row at the database instead. The evaluator now treats the tenant id as the Hibernate binders already do: it keeps the constraints declared on it, and gives it no default constraints, so an entity that saves without a current tenant and declares none on its tenant id saves as before. When validation cascades to a new associated object in discriminator mode, its tenant id is not checked while it is still unset, since multi-tenancy assigns it as the object is inserted, after the cascade. Fixes apache#14365
matrei
left a comment
There was a problem hiding this comment.
Thanks, this is a careful fix and it matches what we agreed on the issue: only the constraints declared on the tenant id are checked, no default nullable, no global '*' constraints, and no constrained property when nothing is declared. Keeping canPropertyBeConstrained and isConstrainableProperty as they are is right. The PersistentEntityValidator change is mode-aware without needing anything new, because PersistentEntity.getTenantId() is only set in DISCRIMINATOR mode.
I ran the new specs and the full test suites of grails-datamapping-validation, grails-datamapping-core-test and grails-data-hibernate5-core locally, and they all pass. Without the fix, 13 of the new cases fail. With only the evaluator change, the parent-with-new-child cases fail, so the tests cover both parts of the change.
7.0.x is the right target. The touched code is the same on 7.1.x, 7.2.x and 8.0.x. The diff applies cleanly to 7.1.x and 7.2.x. On 8.0.x there is one small conflict, in the imports of DefaultConstraintEvaluatorSpec and a neighbouring feature method, and the fix is to keep both sides. There is also the docs sentence about nullability that you already flagged.
A few things before merging:
-
Licensing checkbox. "I have the necessary rights to submit this contribution and confirm it is my own original work" is unchecked. Could you confirm it, or tell us what's holding you back? We can't merge without it.
-
MongoDB question. I'm fine with handling this in a follow-up. Both cases need data that already breaks a constraint declared on the child's tenant id. Also, cancelling an insert that fails validation without an error is how
ValidationEventListeneralready treats any entity on MongoDB, so this PR only adds one more constraint that can trigger it. Please open an issue with the two scenarios you described and link it here. -
Upgrade notes. No entry is needed in the upgrade guide for a patch release, but the behavior change should be in the release notes (see the title suggestion below).
-
Title (optional). Release Drafter uses the PR title for the release notes. Something like "Validate the constraints declared on a multi-tenant entity's tenant id" would read better there than "Check the constraints declared on a tenant id".
Inline comments below.
| // In discriminator mode, the only mode in which an entity has its tenant id set, multi-tenancy assigns the tenant id | ||
| // of an associated object as it is inserted, after this cascade, so one that is still unset is not checked here. | ||
| // Inside Tenants.withoutId it is not assigned then, which this module cannot tell |
There was a problem hiding this comment.
"In discriminator mode, the only mode in which an entity has its tenant id set" can be read as "the only mode in which the object has a tenant id value". It means PersistentEntity.getTenantId(). Maybe:
// PersistentEntity.getTenantId() is only set in DISCRIMINATOR mode, where multi-tenancy assigns the tenant id of an
// associated object as it is inserted, after this cascade. An unset tenant id is therefore not checked here. Inside
// Tenants.withoutId nothing assigns it, which this module cannot tell.(The last sentence of the current comment is also missing its period.)
| then: | ||
| saved | ||
| !owner.hasErrors() | ||
| owner.pets*.firmId == ['acme'] |
There was a problem hiding this comment.
This case is about the child not being lost, so please assert that it was persisted, not just that its firmId was set:
Pet.withNewSession { Pet.count() } == 1That also guards against the silent-cancel behavior from the MongoDB question if this datastore ever registers ValidationEventListener.
There was a problem hiding this comment.
Added Pet.withNewSession { Pet.count() } == 1 in 5407e3b.
| then: | ||
| !owner.hasErrors() | ||
| owner.id != null | ||
| owner.pets*.firmId == ['acme'] |
There was a problem hiding this comment.
Same here: TenantPet.count() == 1.
There was a problem hiding this comment.
Added TenantPet.count() == 1 in 5407e3b.
| } | ||
| ---- | ||
|
|
||
| Constraints declared on the tenant identifier, such as `nullable` or `maxSize`, are checked when an instance is validated, after the current tenant id has been assigned to it. See <<tenantIdConstraints,Validating the Tenant Id>>, also for the cases where no tenant id is assigned, as inside `withoutId`. The tenant id column is not nullable unless `nullable: true` applies to the tenant identifier, declared on it or in `grails.gorm.default.constraints`, so the database rejects an instance saved without a tenant id that validation lets through. |
There was a problem hiding this comment.
This paragraph does three things at once, and the last sentence is hard to follow. Suggest splitting it:
Constraints declared on the tenant identifier, such as `nullable` or `maxSize`, are checked when an instance is validated, after the current tenant id has been assigned to it. See <<tenantIdConstraints,Validating the Tenant Id>>, which also covers the cases where no tenant id is assigned, such as inside `withoutId`.
The tenant id column is not nullable unless the tenant identifier is constrained with `nullable: true`, either on the property or in `grails.gorm.default.constraints`. Validation does not give the tenant id a default `nullable: false`, so an instance saved without a tenant id can pass validation and still be rejected by the database.Reword the comment on the cascade check, assert that a new associated object saved with its owner is persisted, and split the paragraph on the tenant id column in the discriminator docs.
|
Thanks for the review. 5407e3b makes the four inline changes. The full test suites of
|
jdaugherty
left a comment
There was a problem hiding this comment.
Verified at 7a78c7b: the four new specs pass (22 cases). With DefaultConstraintEvaluator and PersistentEntityValidator reverted to the 7.0.x base, 13 of them fail (5 evaluator, 1 discriminator-mode core, 3 no-mode core, 4 Hibernate 5), so the specs pin both halves of the change. The full grails-datamapping-validation, grails-datamapping-core-test and grails-data-hibernate5-core suites are green on this head, and Checkstyle and CodeNarc are clean for the touched module.
The approach is the right one for a patch: the continue keeps the tenant id out of both the derived branch and applyDefaultConstraints, applySharedConstraints still runs on it, and the cascade skip is scoped to DISCRIMINATOR mode through PersistentEntity.getTenantId(). I also traced the column side of the new docs paragraph: the mapping builder applies the class's constraints closure and the grails.gorm.default.constraints closure to the tenant id's PropertyConfig before createDerivedPropertyMapping wraps it, so the schema does follow nullable: from either place while validation ignores the '*' defaults, as the docs now say.
I agree with the asks in matrei's review, including a follow-up issue for the MongoDB cases rather than handling them here. One thought for that issue, not for this PR: if the multi-tenancy listener assigned the tenant id to cascade-validated associations on the ValidationEvent, as it does for the top-level instance, the cascade would need no skip, the owner's validate() would report a child's unset tenant id inside withoutId, and the insert-time cancel on MongoDB would not be reached.
One addition inline: the importFrom path is the one branch the change affects that no spec covers.
| } | ||
|
|
||
| @Issue('https://github.com/apache/grails-core/issues/14365') | ||
| void 'a tenant id gets a shared constraint declared on it, but not the global default constraints'() { |
There was a problem hiding this comment.
The release notes say importFrom now carries the constraints of a tenant id in both directions. That is the one path through evaluate that the new continue changes without a spec: ConstrainedPropertyBuilder.handleImportFrom evaluates the source class with this evaluator and copies every applied constraint onto the target node, and before this change the derived branch removed that node again when the target was a tenant id.
Could you add a case here that pins both directions: a class with importFrom TenantCustomer, whose firmId ends up nullable: false with maxSize == 5, and a multi-tenant class whose constraints importFrom a class that constrains the property mapped as its tenant id, where the tenant id keeps the imported constraints and still gets nothing from the '*' entry of defaultConstraints. Non-blocking.
There was a problem hiding this comment.
Added in f0a2630, in both directions:
CustomerCommand, which is not an entity, doesimportFrom TenantCustomer, and itsfirmIdends upnullable: falsewithmaxSize == 5.- A tenant id that imports keeps the imported constraints.
The second half of what I asked for does not hold as I worded it. importFrom copies every constraint applied to the source property, and for a class that is not an entity that includes its default constraints. A tenant id that imports from such a class therefore does get blank: false from the '*' entry, and the default nullable, through the import. The spec pins that, and it pins "nothing from '*'" where it can be observed: a tenant id that imports from the tenant id of another multi-tenant class (TenantArchive from TenantOrder) gets the declared maxSize alone.
With the evaluator change reverted, both features fail.
jamesfredley
left a comment
There was a problem hiding this comment.
Constraints declared on a tenant id are validated. A cascade in discriminator mode still skips an unset tenant id, so an insert can assign it. Not approving. On MongoDB that later validation can drop a new child while the owner's save still succeeds.
In discriminator mode the validation cascade skipped the unset tenant id of an associated object, since multi-tenancy assigned it only as the object was inserted. GORM for MongoDB validates an instance again as it is inserted, now with its tenant id, and cancels the insert without an error when that fails. A current tenant id that broke a constraint declared on the tenant id of a new associated object therefore left the owner saved and the associated object dropped, while save() reported success. The multi-tenancy event listeners now assign the tenant id of the associated objects that validation cascades to when their owner is validated, as they already do for the owner itself. The cascade then checks the tenant id each object is inserted or updated with, so such a tenant id is a validation error of the owner on every datastore, and PersistentEntityValidator needs no special case for the tenant id. Inside Tenants.withoutId, where nothing assigns it, an associated object whose tenant id is declared nullable: false and not set fails the validation of its owner as well. See apache#16855
A multi-tenant entity names its tenant id with tenantId name: 'firmId' in
the mapping, which registers a property config under the tenantId key, and
otherwise its tenant id is the tenantId property. Declaring constraints on
that property, as tenantId nullable: false does, or configuring it in the
mapping registers a config under the same key, without a name. Such a
config matched no property, so the entity failed to initialize in
discriminator mode ("is multi tenant but does not specify a tenant
identifier property"), and in the other modes the property was mapped as a
plain property instead of the tenant id.
A config under the tenantId key that names no property now stands for the
tenantId property itself, so the constraints declared on a tenant id of
that name are checked like those of one named in the mapping.
importFrom evaluates the class it imports from and copies the constraints applied to each property, so the constraints kept on a tenant id reach it in both directions: a class that is not an entity gets those declared on the tenant id of the multi-tenant class it imports from, and a tenant id keeps those it imports, with no default constraints of its own.
jamesfredley
left a comment
There was a problem hiding this comment.
A new child reached through one cascading association is given its tenant id before validation, so a tenant id that fails a declared constraint fails the owner's save. Not approving. The child is marked visited before the cascade check, so a non-cascading association to that same child blocks the assignment. On MongoDB the insert is still dropped while the owner's save succeeds. validate(deepValidate: false) also walks the children and rewrites an existing child's tenant id.
…d saved When an owner is validated in discriminator mode, the multi-tenancy event listeners assign the current tenant id to the associated objects that are validated with it. Three cases were wrong: - An object that two to-one associations refer to was marked as visited by the first one, also when that association does not cascade validation, as one mapped with cascadeValidate: 'none'. The second one then never assigned the tenant id, although the validator cascades through it. On MongoDB a current tenant id that broke a constraint of that object left the owner saved and the object dropped. The traversal now follows the order of checks of PersistentEntityValidator. - validate(deepValidate: false) and save(deepValidate: false) do not validate the associated objects, but they were given the current tenant id, which replaced the tenant id of an existing object. ValidationEvent now says whether the validation cascades, GormValidationApi and the Hibernate 5 validation and instance APIs set it from the deepValidate argument, and the listeners leave the associated objects alone when it does not. - An associated object without changes is validated but not updated. Giving it the current tenant id replaced the one it had and made it dirty, so it was updated with a tenant id its owner's save would not have written before. Such an object now keeps its tenant id. One without a tenant id is still given one: Hibernate tracks the changes of a new object from the save on, before it is inserted, and the in-memory datastore does not read the tenant id of a loaded object back. The upgrade notes list the changes to the validation of a tenant id. See apache#14365
jamesfredley
left a comment
There was a problem hiding this comment.
The new head fixes the two earlier bugs. A non-cascading association no longer blocks tenant assignment through a second association, and shallow validation no longer rewrites an existing child's tenant id. Threads PRRT_kwDOAAfRJ86z4BrT and PRRT_kwDOAAfRJ86z4BrZ resolved. Not approving. A child created by a cascaded beforeValidate still misses its tenant id, and a child whose only change is inside an embedded is treated as unchanged.
jdaugherty
left a comment
There was a problem hiding this comment.
@jamesfredley both findings of your review of f0a2630 are fixed in 75cd52e.
- Visited before the cascade check: the traversal now follows the validator's order of checks, so an association that does not cascade validation leaves the object to one that does.
deepValidate: false:ValidationEventnow says whether the validation cascades, and the listeners leave the associated objects alone when it does not.
The second finding has a sibling that the same commit fixes. A validation that does cascade also replaced the tenant id of a child that has no changes. That made the child dirty, so it was then updated with the current tenant id, which the save of its owner did not do before this PR. An associated object that has a tenant id and no changes now keeps it.
75cd52e also adds note 22 to the upgrade notes, for the changes of this PR. The details are in the two threads, and the description has the evidence and the notes for the merge to 8.0.x.
…o it The multi-tenancy event listeners collected the associated objects of an instance before it was validated, and gave each the current tenant id. Two cases were wrong: - An object that the beforeValidate callback of an associated object creates did not exist yet when the objects were collected. It was validated without a tenant id, so a tenant id declared nullable: false failed the save of the owner. PersistentEntityValidator now calls a listener with each associated object it cascades to, once the beforeValidate callback of that object has run and before its constraints are checked. The listeners register one on the ValidationEvent, the validation APIs pass it to the validator, and the tenant id is assigned there. The listeners no longer walk the associations themselves. - An associated object that has a tenant id keeps it when it is not saved with its owner, which hasChanged() alone decided. An object whose only change is inside an embedded object is updated as well, with the current tenant id, which was then not validated. The core listener now asks the session, as the persisters do before an update, and the Hibernate 5 listener uses the check of GrailsEntityDirtinessStrategy. Hibernate also updates a versioned object when one of its collections has changed, which the Hibernate 5 listener checks too. See apache#14365
jdaugherty
left a comment
There was a problem hiding this comment.
@jamesfredley both findings of your review of 75cd52e are fixed in f02c0c8.
- A child created by a cascaded
beforeValidate: the validator now tells the multi-tenancy listeners about each associated object as it comes to it, after thebeforeValidatecallback of that object and before its constraints. The listeners no longer collect the objects up front, so they no longer repeat the validator's traversal. - A child whose only change is inside an embedded object: the listeners now use the check with which the datastore decides whether to update an object.
Looking for other updates that hasChanged() does not see, I found one more on Hibernate: a versioned object is updated when one of its collections has changed. f02c0c8 covers that as well. The details are in the two threads, and the description is updated.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. A nested validate still sees the outer cascade listener, so an unrelated child is assigned the outer tenant. A child whose embedded beforeValidate runs after the dirtiness check is still treated as unchanged. A child created by a cascaded beforeValidate now gets its tenant id, and an embedded change already present when validation reaches the child is seen.
…e end PersistentEntityValidator calls a cascade listener with each associated object, and the multi-tenancy event listeners assign the tenant id there. Two cases were wrong: - The listener was held for the thread while a validation ran. A validation that a callback started with a validate method that takes no listener still saw it, so an unrelated object was given the tenant id of the validation around it, and its nullable error was not reported. A validation now takes its listener as it starts and passes it along its own cascade. One that runs meanwhile calls the listener it is given itself, or none. - An associated object that has a tenant id keeps it when it is not saved with its owner, which was decided before the validation reached the objects below it. A callback that ran later, such as the beforeValidate of an embedded object, could change the object, which was then updated with a tenant id that was not validated. The listener now returns whether it has changed the object. The validator passes an object that it has left alone to it again once every associated object has been validated, until it leaves them all alone, and checks the constraints of an object that it changes then again. See apache#14365
jdaugherty
left a comment
There was a problem hiding this comment.
@jamesfredley both findings of your review of f02c0c8 are fixed in d047482.
- A nested validation saw the outer listener: a validation now takes its listener as it starts and passes it along its own cascade. A validation that a callback runs sees the listener it is given itself, or none.
- A child that a later callback changes: the listener is asked again about each object it has left alone once every callback of the validation has run, and the constraints of an object it changes then are checked again.
The details are in the two threads, and the description is updated.
The jobs that failed on 06372c3 did not get as far as this change. They failed as they resolved the plugins of the build, where repo.grails.org answered 429 Too Many Requests, so they need a rerun.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. A second pass assigns the current tenant but keeps the error from the old tenant. A read-only child is given the current tenant even though Hibernate will not update it. A nested validate no longer sees the outer cascade listener. A child dirtied by an embedded beforeValidate is asked again. Threads PRRT_kwDOAAfRJ860EXTH and PRRT_kwDOAAfRJ860EXTL resolved.
…ne alone PersistentEntityValidator passes an associated object that a cascade listener has left alone to it again at the end, and checks the constraints of one that the listener changes then again. Two cases were wrong: - The constraints of such an object were checked with the tenant id it had, and an error that they recorded then stayed. The second check skips a property that has an error, and an error cannot be taken out of the errors again, so the owner failed validation for a tenant id that the object no longer had. A validation with a listener now records its errors in a copy of the given errors. The errors that the constraints of an object recorded are left out of the copy when the object is checked again, and what the copy holds at the end is added to the given errors. - With Hibernate, an associated object that is read-only in the session, such as one that read(id) has loaded, was given the current tenant id when it had changes, although Hibernate does not update it. A current tenant id that broke a constraint of that object then failed the save of its owner. A read-only object that has a tenant id now keeps it. See apache#14365
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. A read-only child whose tenant is null is still given the current tenant. The earlier stale error is gone. A read-only child that already has a tenant is left alone.
A further review of the tenant id validation found these, which this fixes: - The validator recorded its errors in a copy whenever a cascade listener was registered, so a constraint that reads the errors of the instance did not see the errors recorded before it. With GORM for Hibernate, the given errors are the errors of the instance. The errors are recorded in the given errors again. Only when the listener changes an object whose constraints had recorded errors does validate(Object, Errors, boolean, BiPredicate) return a copy without them, which the validation APIs then use as the errors of the instance. - An object that two associations refer to was validated twice when the listener changed a property its hashCode depends on, such as its tenant id. The validated objects are also tracked by identity. - Validating an instance of a class that is not multi-tenant threw TenantNotFoundException when no tenant was current. Both listeners now leave an associated object alone then, as it gets its tenant id as it is inserted or updated. - The Hibernate 5 listener now counts only the changes Hibernate stores. A change to a property it does not map gave the object the current tenant id, which Hibernate then wrote. It also treats an object whose insert waits for the flush as saved, which a second validation left with a tenant id that the insert replaced. An object that Hibernate does not update keeps its lack of a tenant id too, also when it is read-only. - The cascade listener is also given the association through which the validation reaches the object. The core listener counts only the own changes of the object of a to-one association, as GORM for MongoDB saves such an object only then; a change inside an embedded object no longer gives it the current tenant id and makes it updated. - GORM for Hibernate filters by the column that the mapping gives the tenant id. With tenantId column: 'x', or tenantId name: 'firmId' and firmId column: 'x', every query of the class failed. Upgrade note 22 said that nothing changes when validation does not cascade, and that GORM for MongoDB used to drop a child. The tenant id constraints are now checked by the validation that GORM for Hibernate and GORM for MongoDB run as they write an instance that was not validated with the instance being saved, which skips the write when it fails. The note and the guides now say so, and the specs pin it. The note also corrects how to keep the previous result, and says what else changes for a tenantId property in the other modes. The MongoDB and Neo4j guides describe the tenant id constraints. See apache#14365
|
@jamesfredley the finding of your review of 78e6d1c is fixed in 1ffa9ef: an associated object that Hibernate does not update keeps its lack of a tenant id too, read-only or not. The details are in the thread. A further review of 78e6d1c on my side found more, which the same commit fixes:
One behaviour is documented rather than changed. With The description has the evidence: the 26 cases that failed before the fix, and 26 mutations, each caught. |
jamesfredley
left a comment
There was a problem hiding this comment.
Not approved. A new child whose change tracking has been reset is treated as already saved, so its tenant stays unset and a nullable: false tenant fails the owner's save. A read-only child whose tenant is null is left alone. A later pass no longer keeps the error from the old tenant.
A new associated object after trackChanges() is not in the session and has no tracked changes, so the Hibernate 5 listener took it for one that is not saved. It got no tenant id, and a tenant id declared nullable: false failed the save of its owner, although the same save without cascading validation inserts the object. An object outside the session now counts as saved when Hibernate takes it for a new one as a save cascades to it. The persister answers from the identifier and the version of the object, and an object with an assigned identifier and no version is looked up in the database. A detached object without changes still keeps its tenant id. See apache#14365
|
@jamesfredley the finding of your review of 1ffa9ef is fixed in bab977c: a new associated object whose tracked changes were reset now counts as one that Hibernate inserts, so it is given the current tenant id before it is validated. The details are in the thread. |
jamesfredley
left a comment
There was a problem hiding this comment.
A new Hibernate child whose change tracking was reset is now treated as new, and a read-only child is left alone. Not approving. A new child whose tracking was reset still keeps the wrong tenant when only changed properties are written, and a Hibernate child whose only change cannot be updated is still given the current tenant.
A review found two cases where an associated object was validated with a tenant id other than the one stored for it: - The core listener kept the tenant id of a new object whose tracked changes were reset, although it is inserted with the current one. An object without an identifier now counts as new. With GORM for MongoDB the tenant id it is given counts as a change, so such an object of a to-one association is now inserted when that id differs from the one it had. - The Hibernate 5 listener assigned the current tenant id whenever a mapped property had changed. Hibernate updates the row only when the object has a version or the property is updateable, so with version false a change to an updateable: false or formula property writes nothing. An update of a class mapped with dynamicUpdate writes the changed columns alone, which a tenant id never counts as, so such an object keeps its tenant id. See apache#14365
|
@jamesfredley both findings of your review of bab977c are fixed in 8b491a0: a child without an identifier now counts as new in the core listener, and the Hibernate listener follows when Hibernate writes the tenant id of an updated object, which also covers |
jamesfredley
left a comment
There was a problem hiding this comment.
A new child whose tracking was reset is now treated as new when it has no identifier. Not approving. A new child with an assigned identifier still keeps the wrong tenant, and a child that will not be written is still given the current tenant.
A review found two more cases where an associated object was validated with a tenant id other than the one stored for it: - The core listener took a new object with an assigned identifier for an existing one when its tracked changes were reset. A datastore inserts an object with an assigned identifier that the session does not know, so such an object now counts as new. - Both listeners gave the current tenant id to a changed object that the save does not write. Hibernate writes a detached object only when the association cascades the save to it, and GORM for MongoDB saves the objects of a collection only then. Such an object now keeps its tenant id. See apache#14365
|
@jamesfredley both findings of your review of 8b491a0 are fixed in 42f3697: a child with an assigned identifier that the session does not know now counts as new, and both listeners leave a changed child alone when the save does not reach it. The details are in the two threads. |
jamesfredley
left a comment
There was a problem hiding this comment.
A new child with an assigned identifier is now treated as new. Not approving. A new child that will not be saved is still given the current tenant.
A review found that the Hibernate 5 listener gave the current tenant id to a new associated object in an association that does not cascade the save, such as one mapped with cascade: 'none', so its owner failed validation with a tenant id that the object is never stored with. Hibernate inserts a transient object only when the save cascades to it, so the listener now asks the cascade before it takes such an object for a new one. See apache#14365
|
@jamesfredley the finding of your review of 42f3697 is fixed in a31cc21: a new child is now given the current tenant id only when the save cascades to it. The details are in the thread. |
🚨 All tests passed but jobs failed 🚨Failed Jobs without Test Failures❌ Build Health / Forge Projects 🏷️ Commit: a31cc21 Rerun ControlsClick the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
matrei
left a comment
There was a problem hiding this comment.
Thanks for all the work since the last round. The specs are thorough, and the evaluator change we agreed on is still the core of the fix. At a31cc21, all tests of grails-datastore-core, grails-datamapping-validation, grails-datamapping-core-test and grails-data-hibernate5-core pass locally for me.
I want to revisit the target branch, though. When I said 7.0.x was right, the change was the evaluator plus a ten-line skip in the cascade. It is now about 600 lines of main code in four modules, with new public API on ValidationEvent and PersistentEntityValidator, and I don't think it belongs in a patch release any more:
-
The approach has a long tail. The listeners now predict, at validation time, what each datastore will write for each associated object. For Hibernate that means re-deriving its internals: entry modifiability, inserts that wait for the flush, cascade styles,
dynamicUpdate,updateable/formulawith and without a version, and dirty collections of versioned classes. The core listener does the same for MongoDB and the in-memory datastore. Each of the ten review rounds since Nov 4 has found new cases, most of them a wrong prediction. Each was fixed, but I'd rather the next one is found on a development line than by users of a 7.0.x patch. -
Merging up to 8.0.x isn't mechanical any more. As the description says, the Hibernate 7 listener, validation and instance APIs, and binder need the same changes inside the merge. Without the listener port, 8.0.x regresses: a parent saved with a new child whose tenant id is declared
nullable: falsefails validation on Hibernate 7, because the validator no longer skips an unset tenant id. The 8.0.x core listener also needs ahasCurrentSession()guard that can't be tested on 7.0.x. That is a lot of untested work to put into a merge commit. -
It bundles separate changes. I'd split them out:
- The
GrailsDomainBinderfilter column fix stands on its own: queries fail on 7.0.x today withtenantId name: 'firmId'andfirmId column: 'x'. That could go to 7.0.x as a small PR right away. - The
isTenantIdchange fixes the startup failure inDISCRIMINATORmode. It also reclassifies a constrainedtenantIdproperty inDATABASE,SCHEMAand no-tenancy mode: fields and scaffolding stop rendering it, GraphQL stops taking it as input,hasChanged('tenantId')reportsfalse, and the global constraints no longer apply. That's a behavior change of its own, and it deserves a separate PR and decision (inline comment below).
- The
-
validate()gains side effects. It now assigns tenant ids to associated objects, and records them as changes, even when nothing is saved afterwards. On Hibernate it can also query the database (inline comment below). The upgrade note covers the first part, but I'd like us to decide deliberately thatvalidate()may do this. -
Neo4j isn't covered. It uses the core listener, but it is a separate build that CI doesn't run, and the description says its tests weren't run.
The bug isn't a regression: the constraints have been dropped since multi-tenancy was added, and there is a workaround, so there's no urgency to fix it in a patch release. My proposal:
- Split the binder fix out to 7.0.x.
- Move the tenant id constraints and the cascade assignment to 9.0.x. Since 8.0.0 shipped, 8.0.x is a patch line too. A change with this many behavior changes and edge cases is best released in a major, where users read the upgrade notes, and in a milestone first, so it gets real use before 9.0.0. Hibernate 5, Hibernate 7 and MongoDB are all on 9.0.x, so the Hibernate 7 listener can be written and tested in the same PR instead of in a merge.
- Give the
tenantIdclassification change its own PR against 9.0.x as well. InDATABASE,SCHEMAand no-tenancy mode it changes a plain property that works today.
@jdaugherty @jamesfredley what do you think?
| if (propertyName == null) { | ||
| // The mapping or the constraints configure the tenantId property itself, as | ||
| // tenantId nullable: false does, and name no other property with tenantId name: | ||
| propertyName = GormProperties.TENANT_IDENTITY; |
There was a problem hiding this comment.
This fixes the startup failure in DISCRIMINATOR mode, but it also changes what a constrained tenantId property is in every other mode: it becomes a tenant id instead of a plain property. As the upgrade note says, fields and scaffolding stop rendering it, GraphQL stops taking it as input, and hasChanged('tenantId') reports false. That's a separate behavior change from the constraints fix, so I'd prefer it in its own PR. Also, with hasChanged('tenantId') reporting false, does GORM for MongoDB still write a changed tenantId on update in DATABASE mode, where the app sets it itself?
| if (isTransient != null) { | ||
| return isTransient; | ||
| } | ||
| return session.getPersistenceContext().getDatabaseSnapshot(persister.getIdentifier(object, session), persister) == null; |
There was a problem hiding this comment.
For a detached child with an assigned identifier and no version, this runs a SELECT during validate(). Hibernate does the same on a save cascade, but a plain owner.validate() now queries the database too, once for each such child. Worth noting in the docs, or avoiding outside a save.
|
Thanks @matrei, that split makes sense to me. The change has grown well past the small evaluator fix this started as, and finding the next edge case on a development line is better than finding it in a 7.0.x patch. I can open the |
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. A grandchild behind an association the save does not cascade to still gets the current tenant id.
| } | ||
| } | ||
| else if (session != null) { | ||
| if (!cascadesSave(sessionFactory, association)) { |
There was a problem hiding this comment.
A new root owns a new child with cascade none, and that child owns a new grandchild with cascade save-update. The grandchild's tenant id is beta, and its maxSize is 5. Saving the root while the current tenant id is a-tenant-too-long returns null and changes the grandchild's tenant id. The save never writes the grandchild. Leave it alone.
|
@hk2166 thanks, please go ahead with the
@jdaugherty, for the rest: 9.0.0-M1 is scheduled to be released today, so the tenant id constraints and the cascade assignment won't be in it. That leaves two options, and since most of the code is yours, I'd like your view:
jamesfredley's latest finding is a new grandchild behind an association the save doesn't cascade to, which still gets the current tenant id although the save never writes it. That's another case of the long tail I mentioned in my review, so it's worth weighing how much use the change gets before a release. On either branch, the Hibernate 7 listener can go in the same PR, and the |
|
@hk2166 a note on overlap: #17136 (opened after this pull request) changes |
Description
Fixes #14365 and #16855. The tenant id of a multi-tenant entity ignored the constraints declared on it:
validate()passed for aCustomerwithout afirmId, or with one longer than five characters. Hibernate then rejected the row at the database (NULL not allowed, or a value too long) instead of reporting a validation error.Cause:
MappingFactory.createTenantIdmaps every tenant id as a derived property, and has done so since multi-tenancy was added.DefaultConstraintEvaluatordrops the constraints of derived properties, logging "Derived properties may not be constrained". The Hibernate binders already make an exception for the tenant id (mappedForm.isDerived() && !(grailsProp instanceof TenantId)), so the schema applied the declared constraints and only validation skipped them.This targets 7.0.x, as asked on the issue, and takes the narrower option agreed there: only the constraints declared on the tenant id are checked.
Commits 199da8a, ff661fb, f0a2630, 75cd52e, f02c0c8, d047482, a7a143a, 78e6d1c, 1ffa9ef, bab977c, 8b491a0, 42f3697 and a31cc21 were pushed by a maintainer (jdaugherty) in response to the reviews. They replace the cascade's skip of an unset tenant id with the listener change below, let a tenant id named
tenantIdbe constrained, coverimportFrom, limit the listener change to the associated objects that are validated and saved with their owner, have the validator tell the listeners about those objects, replace the errors of an object that is checked a second time, leave a read-only object alone with Hibernate, record the tenant id that validation assigns as a change, so that MongoDB stores it as before, record the errors of a validation in the given errors again, follow how Hibernate and MongoDB write an associated object, filter by the column that the mapping gives the tenant id, treat a new object whose tracked changes were reset as new on every datastore, follow when Hibernate writes the tenant id of an updated object, and leave alone an object, new or not, that the save does not reach.Changes
DefaultConstraintEvaluator: aTenantIdskips both the derived branch and the default-constraints branch. It keeps the constraints declared on it, including asharedconstraint, and gets no default constraints:nullable, so a tenant id that declares onlymaxSizestays nullable;'*'constraints fromgrails.gorm.default.constraints;canPropertyBeConstrainedandisConstrainablePropertyare unchanged.MultiTenantEventListener(the core listener, which the in-memory datastore, MongoDB and Neo4j use, and the Hibernate 5 listener): in discriminator mode, when an instance is validated, the listener now also assigns the tenant id of the associated objects that are validated and saved with it, as it already did for the instance itself. Those objects are validated with their owner, without aValidationEventof their own, so until now they got their tenant id only as they were inserted or updated, after the cascade. The listener now registers a cascade listener on theValidationEvent, and the validator calls it with each associated object it cascades to, once thebeforeValidatecallback of that object has run and before its constraints are checked. The cascade therefore checks the tenant id each object is saved with:beforeValidatecallback creates. It does not walk the associations itself;deepValidate: false) calls no listener, so the associated objects keep what they have until they are inserted or updated;Session.isDirty), as the persisters do before an update. For the object of a to-one association it asks the object itself (hasChanged()), since GORM for MongoDB cascades a save to such an object only when it has changes of its own. The listener is told the association for that;EntityEntry.isModifiableEntity()): one loaded withread(id)or by a read-only query. It assigns one whose insert waits for the flush (EntityEntry.isExistsInDatabase()), as with an identifier from a sequence. For any other object it uses the check ofGrailsEntityDirtinessStrategy: a change to a property that Hibernate maps, any change of an object that has alastUpdatedproperty, or a changed embedded object. It also checks for a changed collection of a versioned object, which Hibernate updates to increment its version. A change to a property that Hibernate does not map, such as an untyped one, does not count;beforeValidateof an embedded object, may have changed it. When it is given the current tenant id then, its constraints are checked again, and the errors that they recorded with the tenant id it had are not reported. An object that still has no changes is left alone again;DirtyCheckable.markDirty). GORM for MongoDB writes the changed properties of an object that it updates, and takes a property that a listener sets as the update starts as changed, which is how it stored the tenant id. Now that the tenant id is set as the owner is validated, it would otherwise be stored as it was. An object that is not updated is left without changes, and so is one that is marked as changed as a whole, all of which is written.PersistentEntityValidator.validate(Object, Errors, boolean, BiPredicate<Object, Association>)(@since 7.0.18): validates with a listener for the associated objects that the validation cascades to. The existingvalidatemethods are unchanged:beforeValidatecallback of that object and before its constraints are checked, and returns whether it has changed the object;Errorsobject, so the method then returns a copy of the given errors without them, holding the errors recorded since, and the validation APIs use that copy as the errors of the instance. Otherwise it returns the given errors;hashCodedepends on, such as its tenant id. The validated objects are also tracked by identity;validatemethod it uses.ValidationEvent(@since 7.0.18):addCascadeListener(BiPredicate<Object, Association>)lets a listener of the event register for the associated objects, andgetCascadeListener()gives the validation APIs the listener to pass to the validator.isDeepValidate(), with its setter, tells whether the associated objects are validated with the object of the event.GormValidationApiand the Hibernate 5 validation and instance APIs set it from thedeepValidateargument ofvalidateandsave, and pass the cascade listener to the validator.AbstractGormMappingFactory.isTenantId: a property namedtenantIdis the tenant id also when the constraints or the mapping configure it.tenantId nullable: falseinconstraints, ortenantId index: trueinmapping, registers a property config under thetenantIdkey. That is the key under whichtenantId name: 'firmId'names another property, and a config without a name matched no property. InDISCRIMINATORmode the entity then failed to initialize ("is multi tenant but does not specify a tenant identifier property"), and in the other modes the property was mapped as a plain property instead of the tenant id.GrailsDomainBinder(Hibernate 5): the filter of a multi-tenant class uses the column that the mapping gives the tenant id. It used the default column name, so withtenantId column: 'x', which the previous change makes possible, or withtenantId name: 'firmId'andfirmId column: 'x', which 7.0.x has too, every query of the class failed.Docs, in the multi-tenancy chapter of the Hibernate guide:
nullable: falsemust be set:withoutIdor@WithoutTenant;DATABASEandSCHEMAmode;DISCRIMINATORmode;withoutIdthe child needs its tenant id before the save;deepValidate: falseorvalidate: falsethe associated instances get their tenant id as they are inserted or updated, that Hibernate validates them then, and that one whose tenant id breaks a constraint declared on it is not inserted: the save fails with aHibernateSystemExceptionwhen the database generates its identifier, and the instance is left out without an error when its insert waits for the flush;nullable: trueapplies to the tenant id.Docs in the MongoDB and Neo4j guides: their partitioned multi-tenancy sections say that the constraints declared on the tenant id are checked, and the MongoDB one that an associated instance that is not validated with the instance being saved is not stored when its tenant id breaks one of them.
Upgrade notes: note 22 of the upgrade notes in the Grails guide (
upgrading60x.adoc) lists the changes below, and says how to keep the previous result: configure the column inmappinginstead of declaring constraints, which GORM for Hibernate applies to the column and validation does not check.Release notes: constraints declared on the tenant id of a multi-tenant domain class are now validated. Apps notice this where nothing assigns the tenant id: saves inside
Tenants.withoutId,DATABASEandSCHEMAmode with a tenant id property, and unit tests that don't configureDISCRIMINATORmode. There, a tenant id declarednullable: falsemust now be set before saving. Before, the constraint was ignored: Hibernate stored the row unless the database rejected it, and unit tests let it pass. The same holds for the associated instances of an instance whose class is not multi-tenant, validated while no tenant is current.importFromnow carries the constraints of a tenant id too: a command object that imports from a multi-tenant domain class gets the constraints declared on its tenant id, and a tenant id that imports from another class gets that property's constraints. Asharedconstraint on a tenant id that names no shared constraint now fails, as it does for any other property. InDISCRIMINATORmode the current tenant id is now assigned to the new and the changed associated instances that are validated with an instance, such as a new child saved with its owner, as that instance is validated, and no longer only as they are inserted or updated. An associated instance that is not saved with it keeps its tenant id: one without changes, with Hibernate a read-only one and one whose only changes are to properties that Hibernate does not store, and with MongoDB the instance of a to-one association of which only an object inside has changed. A tenant id that breaks a constraint declared on such a child is now a validation error of the owner on every datastore. Withsave(deepValidate: false)orsave(validate: false)such a child is not validated with its owner. Hibernate and MongoDB validate it as they insert it, as they do any instance that was not validated with the instance being saved, and now check its tenant id too, so it is no longer stored: MongoDB skips its insert without an error, and Hibernate fails the save with aHibernateSystemExceptionwhen the database generates its identifier, or skips the insert without an error when it waits for the flush. A tenant id property namedtenantIdcan now be constrained. Declaring constraints on it, or configuring it inmapping, made the entity fail to start inDISCRIMINATORmode, and mapped it as a plain property in the other modes. It is now the tenant id in every mode, so it gets no default constraints either: where nothing assigns it, atenantIdproperty that declares onlymaxSize, say, may now be left unset. InDATABASE,SCHEMAand no multi-tenancy mode it is also treated as a tenant id otherwise: the fields plugin and scaffolding do not render it, GraphQL mutations do not take it as an input, andhasChanged('tenantId')reportsfalse. With GORM for Hibernate, the filter now uses the column that the mapping gives the tenant id, so a class whose tenant id is mapped to a column of its own can be queried.Tests
TenantIdMappingSpec(grails-datastore-core), in every multi-tenancy mode:tenantIdproperty is the tenant id when nothing configures it, when the constraints do, and when the mapping does;tenantId name:is the tenant id, also when its constraints are declared and the class has atenantIdproperty of its own.DefaultConstraintEvaluatorSpec(grails-datamapping-validation), in every multi-tenancy mode:tenantId;maxSizegets no defaultnullable;With global defaults (
'*': [blank: false]), they don't reach the tenant id, an undeclared tenant id still gets no constrained property, and asharedconstraint applies.importFrom, in both directions:PersistentEntityValidatorSpec(grails-datamapping-validation):beforeValidatecallback of that object and before its constraints are checked;hashCode;validate.ValidationEventSpec(grails-datastore-core): the cascade listener of an event calls every registered listener, also when one before it has changed the object, and also one registered after the cascade listener was obtained, and says whether any of them changed the object; an event without listeners has none.grails-datamapping-core-test, with aSimpleMapDatastoreand validation on:tenantid.TenantIdConstraintsSpec(discriminator mode):maxSizefails, also for a tenant id namedtenantId;nullable: falsepasses;maxSizefails the save of the owner, with the error onpets[0].firmId, and neither is stored;cascadeValidate: 'none', and a current tenant id that breaks itsmaxSizefails the save of the owner;validate(deepValidate: false)leaves the associated objects alone, also one that has another tenant id, andsave(deepValidate: false)gives them the current tenant id as they are inserted;beforeValidatecallback of an associated object creates is given the current tenant id and saved, and so is an associated object that its ownbeforeValidatecallback changes;beforeValidatecallback of its embedded object changes that object, and when thebeforeValidatecallback of an object it owns changes that one, both of which run after the listener was first called with it;nullable: false;hashCodeincludes its tenant id;beforeValidatecallback runs with the two-argumentvalidateof a validator assigns no tenant ids, and reports a tenant id declarednullable: false, while the validation around it still assigns them;notenantid.UnassignedTenantIdConstraintsSpec(no multi-tenancy mode, so no listener assigns the tenant id, as inDATABASEandSCHEMAmode and in unit tests without discriminator mode):nullable: falseis required byvalidate()andsave(), also for a child saved with its owner;maxSizemay be left unset, and itsmaxSizeis checked, also for a tenant id namedtenantId;tenantid.TenantIdConstraintsSpec(grails-data-hibernate5-core), throughHibernateDatastoreand its multi-tenancy listener:validate()andsave()with the assigned tenant id, also for a tenant id namedtenantId;withoutId, a missing id, a valid explicit id, and a too-long explicit id;validate()assigns the child's tenant id, a current tenant id that breaks the child'smaxSizeis a validation error of the owner, and so is a child without a tenant id insidewithoutId;withoutId, a child whose explicit tenant id is too long;validate(deepValidate: false)leaves a new child alone, andsave(deepValidate: false)gives it the current tenant id as it is inserted;withoutId, is left alone byvalidate(deepValidate: false)and bysave(deepValidate: false)while another tenant is current;deepValidate, a child of another tenant keeps its tenant id while it has no changes, and is stored with it, and a changed one is given the current tenant id, as its update gives it;beforeValidatecallback creates is given the current tenant id and saved, whether the callback is the one of an associated object or of the instance that is saved;maxSizeis a validation error of the owner;beforeValidatecallback of its embedded object changes, and the object that child owns, which has no changes, keeps its tenant id;beforeValidatecallback of its embedded object changes that child, it is given the current tenant id, its owner validates and is saved, and the child is stored with the current tenant id;read(id)and then changed, keeps its tenant id while a tenant that breaks itsmaxSizeis current: its owner validates and is saved, and the child is stored as it was. So does a read-only child whose collection has changed, of which Hibernate updates the version alone;lastUpdatedproperty, which Hibernate updates then, is given the current tenant id and is stored with it;validate()andsave();save(deepValidate: false)fails with aHibernateSystemExceptionwhen a new child, inserted as it is saved, has a tenant id that breaks a constraint declared on it;tenantId column:and with a named tenant id;mappingalone is not validated, and keeps its column settings.MongoTenantIdConstraintsSpec(grails-data-mongodb-core), throughMongoDatastore:tenantIdis checked against the constraints declared on it;pets[0].firmId, and no owner or pet document is written;withoutId, an owner and a child are saved with the tenant ids they are given;cascadeValidate: 'none': whichever of the two comes first, a current tenant id that breaks itsmaxSizefails the save of the owner, and neither is stored;beforeValidatecallback of an associated object creates is saved for the current tenant;maxSizefails the save of the owner, and the child is stored as it was;beforeValidatecallback of its embedded object changes;save(deepValidate: false)orsave(validate: false), a new child whose tenant id breaks a constraint is not inserted, without an error; when the session is flushed after the save, neither the owner nor the child is inserted;withoutId, a new child without a tenant id is reported asnullableand keeps none.PersistenceEventListenerSpec(the TCK, which the in-memory datastore, Hibernate 5 and MongoDB run): aValidationEventsays whether the associated objects are validated too, forvalidate(),validate(deepValidate: false)andvalidate(deepValidate: true).Evidence (on 7.0.x, at 1ffa9ef):
PersistentEntityValidatorSpec(20 cases, eleven of them new),ValidationEventSpec(5) and the TCK case on the in-memory datastore, Hibernate 5 and MongoDB.importFromcarries none, validation passes in the in-memory and MongoDB specs, and Hibernate 5 throws aDataIntegrityViolationExceptioninstead of reporting a validation error;save()returned the owner without an error, which is what MongoDB: an associated object saved with its owner is dropped without an error when its tenant id breaks a declared constraint #16855 describes.validate(deepValidate: false), and an object that has a tenant id and no changes.beforeValidatecallback creates or changes, and an object whose only change is inside an embedded object or in a collection.validate:PersistentEntityValidatorSpec, an object that is passed to the listener again, and the repeated pass;save()returned the owner there.beforeValidatecallback, not passing the objects it has left alone again, not checking the constraints again, passing them again only once, and leaving the listener set for a validation that this one runs;hasChanged()alone in the core listener, leaving out the embedded objects or the collections in the Hibernate 5 listener, assigning an object that has a tenant id and is not saved, and skipping an object without changes that has no tenant id;GormValidationApi, in the Hibernate 5 validation API, or in the Hibernate 5 instance API.PersistentEntityValidatorSpec, and the child that a later callback changes, in the in-memory and the Hibernate 5 spec;PersistentEntityValidatorSpecandValidationEventSpec, for the association that the listener is given and the errors that a validation returns;[email, emailConfirm]instead of[email]with Hibernate;TenantNotFoundException, in the in-memory and the Hibernate 5 spec;hashCodeincludes its tenant id: validated twice;deepValidate: falseandvalidate: false, the unversioned child, the column configured inmappingand the tightenedwithoutIdcase pass with those main sources too. They pin behaviour that the main sources at 78e6d1c already had.GormValidationApi, in the Hibernate 5 validation API and in the Hibernate 5 instance API, and not attaching them in either Hibernate 5 API;TenantNotFoundException, ignoring the rule for a to-one association, which the in-memory and the MongoDB spec each catch, and not recording the tenant id as a change;TenantNotFoundException, not treating a pending insert as saved, treating a read-only object as modifiable, counting a change to any property, leaving out thelastUpdatedrule, counting a changed collection of an unversioned object, and skipping the check for an object without a tenant id;GrailsDomainBinder: filtering by the default column.Merging up to 8.0.x (simulated with
git merge-treeat 1ffa9ef):MultiTenantEventListener: keep both imports, keep the newonApplicationEventand the three methods after it, and lethandleEventstart with 8.0.x'sif (isValidSource(event)) {;GormValidationApi.fireEvent: keep 8.0.x's lookup of the publisher, setevent.deepValidate = deepValidatebefore it, and return the event after it;DefaultConstraintEvaluatorSpec, in the imports and a neighbouring feature method: keep both sides;upgrading60x.adoc: keep 8.0.x's side. 8.0.x carries the 7.0.x notes inupgrading80x.adoc, where notes 19 to 21 are notes 87 to 89, so note 22 goes there as the next one.MultiTenantEventListenerneeds the same change as the Hibernate 5 one in that merge:onApplicationEventhandles the event and then registers the cascade listener, withassignTenantIdOfAssociatedObject,isSaved,entryOf,hasStoredChangeandhasDirtyCollectionas in the Hibernate 5 listener. Without it, a parent saved with a new child whose tenant id is declarednullable: falsefails validation on Hibernate 7, since the validator no longer skips an unset tenant id.HibernateGormValidationApiandHibernateGormInstanceApineed the same change as the Hibernate 5 ones in that merge:setDeepValidate(deepValidate)on theValidationEventthey publish, the validator called with the cascade listener of that event, and the errors it returns used as the errors of the instance. Without the first the TCK case fails on Hibernate 7, and without the second the associated objects get no tenant id before they are validated there.AbstractGormMappingFactorymerges into 8.0.x's version ofisTenantIdas it is.GrailsDomainBinderneeds the same fix ofgetMultiTenantFilterCondition.GormValidationApi.doValidatevalidates without a session when none is bound, so the core listener'sisSavedneedsdatastore.hasCurrentSession()before it asks the session. On 7.0.x validation fails earlier without a session, so this cannot be tested here.nullable: false. The same holds for the sentence of the upgrade note about atenantIdproperty that was mapped as a plain property.nullable(ShelfinPersistentEntityValidatorSpecdeclaresname nullable: falsefor that), and don't usewithoutIdingrails-datamapping-core-test, since the core listener assignsDEFAULTthere on 8.0.x. The MongoDB spec useswithoutIdwith explicit tenant ids, which 8.0.x keeps. For a child without one it asserts that the owner reports anullableerror and that the child keeps no tenant id, which fails on 8.0.x, where the core listener assignsDEFAULTinsidewithoutId: that case needs updating at the merge. The Hibernate 5 spec loads instances of another tenant insidewithoutId, which 8.0.x keeps too.DEFAULTinsidewithoutIdfor the in-memory datastore and MongoDB, so there "nothing assigns it" holds only for Hibernate; the new docs section may need a word at the merge.A child saved with its owner on MongoDB (#16855)
The first version of this PR skipped a new child's unset tenant id in the cascade, since it was assigned only on insert. MongoDB validates the child again on insert, then with its tenant id, and cancels the insert without an error when that fails, so the owner was saved and the child was not. The listeners now assign the child's tenant id as the validator comes to the child, so the cascade checks it. In both scenarios of #16855, where the child's tenant id is declared
nullable: false, maxSize: 5, the save of the owner now fails with a validation error on the child's tenant id (pets[0].firmId), and neither is stored:withoutId, the child has no tenant id.The same holds for a child that has a tenant id which the current one replaces. With Hibernate 5, where both saves were rejected at the database, they now fail validation as well.
Verification
grails-datastore-core(105),grails-datamapping-validation(40),grails-datamapping-core-test(603) andgrails-data-hibernate5-core(719) pass on 7.0.x, and so do the multi-tenancy specs ofgrails-data-mongodb-corewith the TCKPersistenceEventListenerSpec(46). The last change of the Hibernate 5 listener was run again with its multi-tenancy specs.grails-datastore-core(100),grails-datamapping-validation(29),grails-datamapping-core(251),grails-datamapping-core-test(585),grails-data-hibernate5-core(697) andgrails-data-mongodb-core(574). They were not run again in full for the commits since, which is left to CI.codeStylepasses for the modules whose main sources changed../gradlew ratpasses. The Hibernate and MongoDB guides build with:grails-data-hibernate5-docs:asciidoctorand:grails-data-mongodb-docs:asciidoctor, and the Grails guide with:grails-doc:publishGuide -x aggregateGroovydoc. The Neo4j guide, which is built separately, was not built../gradlew build --rerun-tasks, and the Neo4j tests, though Neo4j uses the core listener.429 Too Many Requests.Generative AI tooling (Claude Code) was used to research the cause, write the change and its tests, and run the checks. I reviewed the change.
Contributor Checklist
Please review the following checklist before submitting your pull request. Pull requests that do not meet these requirements may be closed without review.
Issue and Scope
7.0.x): Bug fixes only. No new features or API changes.7.1.x): New features are welcome, but breaking existing APIs must be avoided.8.0.x): Reserved for major changes. Breaking API changes are permitted.Code Quality
./gradlew build --rerun-tasks. (Not the full build; all tests of the affected modules pass, see Verification.)./gradlew codeStyleand resolved any violations. See Code Style for details.Licensing and Attribution
Documentation