Repository navigation
Fixes 19778: resolve the team hierarchy in batches, not one Team at a time - #33632
Conversation
…am at a time Reading a user resolved the team hierarchy by loading a full Team entity per node with "defaultRoles, defaultPersona, policies, parents, profile, domains". Each of those loads costs five relationship queries, and because TeamRepository.setFields computes inheritedRoles whenever defaultRoles is requested, each load re-walked its own ancestors with the same field set, which computed inheritedRoles again. The walk re-entered itself once per level, and the whole thing ran once per team the user belonged to. Measured on a four-level hierarchy, one warm GET of a user with teams,roles,domains,personas,defaultPersona cost 58 entity_relationship queries plus 10 for every group the user was in - about 1050 for the 100-group user in the report, for a single read. inAnyTeam(), matchTeam() and hasAnyRole() are rule conditions, so they re-ran that walk once per rule per entity in a listing. TeamHierarchyResolver reads ancestry, default roles, policies and domains straight out of entity_relationship, one batch of queries per level of the hierarchy, and visits each team once. SubjectContext, SubjectCache and the user and team repositories all route through it. SubjectCache additionally keeps the subject's flattened team-name and inherited-role sets, computed from the walk the policy loader already does, so repeated rule conditions cost nothing. The same read is now 39 queries, flat from 1 to 40 groups. The dead UserPolicyIterator, TeamPolicyIterator and RolePolicyIterator go with it: SubjectCache superseded them, and they were where the re-entrant walk lived. hasAnyRole() for team-inherited roles now answers from the 2-minute policy cache rather than the database. Team writes that can change it - defaultRoles, parents, children, users, policies - already call SubjectCache.invalidateAll(), as does RoleRepository, so the only window is cross-pod, which is pre-existing for getPolicies() and deliberately not widened here. MultiTeamUserFanOutIT is the regression guard and fails without this change (68 queries for a 2-group user against 348 for a 30-group user). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
Picks up #33634, which routes the 'Tag and Glossary Selector should close vice versa' Playwright test through openGlossaryPicker. That test fails deterministically against this branch's previous merge base: the picker refactor (#33565) left the glossary trigger on a raw click that does not retry when the react-aria trigger is not ready, and the assertion on the popover treegrid went with it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… race Five findings from the PR review, all on the node cache and the authorization data derived from it. Cross-pod staleness. hasAnyRole() and inAnyTeam() used to read the team hierarchy from the database on every evaluation; they now answer from the summary kept in USER_POLICIES_CACHE, and the registered Invalidatable dropped only USER_CONTEXT_CACHE. A peer could therefore keep granting access through a role removed from a team, or a parent reparented away, until the entry expired. A team, role or policy message now drops the policy cache and the resolved graph as well, and a user message drops that user's policy entry rather than just their context. Role names are copied into resolved nodes, which is the same gap by a different route. Copy cost. detached() JSON round-tripped every reference of every node on every cache hit, and closure() runs two to three times per user read -- so the pathological user this PR targets paid a deep copy of their whole hierarchy several times per request, in the name of a mutation that only one caller can perform. Nodes are immutable now, and only rolesForTeams copies, because only inherited roles reach a caller that stamps an href onto them. Read/write race. A read that started before an invalidation put its pre-write view back afterwards, and it then served authorization for the full TTL. Invalidation bumps a generation the memoizing step rechecks, mirroring the write epoch EntityRepository guards its loaders with. Cache size. The hard-coded 10,000 becomes a 1,000 default sized at startup from authCacheMaxEntries, the same knob as the caches derived from this one. Test concurrency. Only the statement-count test needs @isolated -- it decorates the application-wide SQL logger. The three semantic tests move to TeamHierarchyInheritanceIT and run concurrently, over shared fixtures. Each of the four new guards was confirmed to fail without its fix. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The cache was the source of all three of the review's P1 findings, and each fix
for them added machinery rather than removing risk: a generation counter for the
read/write race, four new remote-invalidation branches, a rule about which
references may be handed out. A per-server cache of authorization data is only
consistent across a load-balanced deployment for as long as every pod receives
every invalidation, and the pub/sub that carries those exists only when Redis is
configured -- CacheBundle returns a NoopCacheProvider otherwise and never builds
it. So the cache bought a five-fold cut on a path the batching had already
fixed, in exchange for a correctness argument that depends on optional
infrastructure.
A read of a user in any number of groups is 38 relationship statements against a
four-level hierarchy, flat from 1 to 40 groups, against 58 + 10 per group before
this branch -- 448 for a 40-group user, and about 1050 for the 100-group user in
the issue. The reported regression is gone either way.
What the cache was doing for repeated rule conditions is kept: inAnyTeam() and
hasAnyRole() still answer from the per-user summary SubjectCache holds, which is
invalidated on the writes that change it, locally and across pods.
Kept from the review fixes, because they guard that summary rather than the
cache that is going away:
- Team, role and policy writes drop the policy cache on every pod, not just
the writing one, and a user write drops that user's entry.
- TeamRepository invalidates on delete and on rename.
If a warm read ever needs to be cheaper than 38, the place to put that is the
shared cache, where one copy is deleted authoritatively on write, rather than a
copy per server that each pod has to be told to forget.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Code Review ✅ No issues found 1 closed / 1 findings🔴 High risk Replaces per-team recursive entity loading with a batched ✅ 1 closed✅ Performance: detached() JSON-deep-copies every node on each closure() call
OptionsDisplay: compact → Counting what did not apply, without listing it. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
|
Thanks — the three P1s were all real, and chasing them led somewhere better than fixing them one at a time. All three existed only because of the per-JVM node cache, so the cache is gone. The decisive fact is that cross-pod invalidation itself requires Redis: Finding by finding:
If a read ever needs to be cheaper than 38, the right home is the shared cache — one copy, deleted authoritatively on write — rather than a copy per server that each pod has to be told to forget. Leaving that as follow-up rather than carrying it here. |
Makes sense — removing the per-JVM cache is the cleaner fix here since it eliminates all three P1s (staleness, missed invalidation on role/policy, read/write race) at the root rather than patching each one, and the numbers back it up: 38 flat relationship statements from 1–40 groups vs. 58 + 10/group before. Confirmed |
| * cache carries the team names and inherited role names {@code hasAnyRole()} and | ||
| * {@code inAnyTeam()} answer from, and both used to be read from the database on every | ||
| * evaluation; if only the writing pod dropped it, a peer would keep granting access through a | ||
| * role that was removed from a team, or through a parent that was reparented away, until the |
There was a problem hiding this comment.
On a no-Redis multi-pod deployment (which we support), peers never receive this invalidation, so inAnyTeam/hasAnyRole go up to 2 min stale here where main read them live — a real authz regression on that config. Rather than reading live again (that reintroduces the #19778 fan-out), can we resolve the hierarchy once per request and reuse it, instead of caching it cross-pod with a TTL? That keeps the fan-out fix and stays fresh without Redis. (The policy list in this cache has the same pre-existing window — separate ticket.)
Describe your changes:
Fixes #19778
Reading a user resolved the team hierarchy by loading a full
Teamentity per node with"defaultRoles, defaultPersona, policies, parents, profile, domains". Each of those loads costs fiverelationship queries, and because
TeamRepository.setFieldscomputesinheritedRoleswheneverdefaultRolesis requested, each load re-walked its own ancestors with the same field set — whichcomputed
inheritedRolesagain. The walk re-entered itself once per level, and the whole thing ranonce per team the user belonged to.
inAnyTeam(),matchTeam()andhasAnyRole()are ruleconditions, so they re-ran that same walk once per rule per entity in a listing.
TeamHierarchyResolverreplaces the per-node entity reads: it reads ancestry, default roles,policies and domains straight out of
entity_relationship, one batch of queries per level of thehierarchy, visiting each team exactly once.
Measured on a four-level hierarchy (Organization → business unit → division → department → N groups),
one warm
GET /v1/users/name/{name}?fields=teams,roles,domains,personas,defaultPersona:The cost used to grow by +10 relationship queries per additional group — roughly 1050 for a
single read by the 100-group user in the issue. It is now flat.
Type of change:
High-level design:
Approach. Authorization needs four facts about a team: its name, its parents, its default roles
and its directly attached policies. Materialising a
Teamentity to get them is what dragged indefaultPersona,profile,domainsand the re-entrantinheritedRolescomputation.TeamHierarchyResolverreads those facts fromentity_relationshipwith a breadth-first walk thatissues a fixed number of queries per level, so the query count follows the depth of the hierarchy
rather than how many teams sit at the bottom of it.
No cache, deliberately. An earlier revision of this PR memoized the resolved nodes per JVM,
which took a warm read from 38 statements to 8. It has been removed. A per-server cache of
authorization data is only consistent across a load-balanced deployment for as long as every pod
receives every invalidation, and the pub/sub that carries those exists only when Redis is configured
—
CacheBundlereturns aNoopCacheProviderotherwise and never constructs it. That bought afive-fold cut on a path the batching had already fixed, in exchange for a correctness argument
resting on optional infrastructure, plus a generation counter for the read/write race, four new
invalidation branches, and a rule about which references may be handed to callers. If a read ever
needs to be cheaper than 38, the place for that is the shared cache, where one copy is deleted
authoritatively on write — not a copy per server that every pod has to be told to forget. Filed as
follow-up work rather than carried here.
Components.
TeamHierarchyResolver(new) —closure(),rolesForTeams(),isInTeam(),teamNamesInHierarchy(),domainsForTeams(). Preserves the semantics it replaces: depth-firstrole order, de-duplication, deleted-entity filtering, cycle safety, and the
organization-as-implicit-parent fallback from
TeamRepository.getParents.SubjectContext—getRolesForTeams,isInTeam,hasRoleandisOwnerUnderTeamdelegate to theresolver. The dead
UserPolicyIterator/TeamPolicyIterator/RolePolicyIteratorare removed:SubjectCachesuperseded them, and they were where the re-entrant walk lived.SubjectCache—loadTeamPolicieswalks the resolved graph instead of loading teams, and thecached
UserPoliciesContextgains aTeamHierarchySummary: the subject's flattened team-name andinherited-role sets, computed from the walk the policy loader already performs.
isUserUnderTeam()and
hasAnyRole()answer from that, so a rule condition evaluated per rule per entity costsnothing rather than re-walking the hierarchy. The summary records the team ids it was built for and
falls back to a fresh resolve when a
SubjectContextwraps aUserthat did not come from thecache, so a caller can never be authorized against the wrong memberships.
UserRepository/TeamRepository— domain inheritance batches through the resolver instead ofone
Entity.getEntity(TEAM, …, "domains")per team, each of which recursed to the root.fetchAndSetRolesresolves the union of a page's teams once rather than once per user, andgetInheritedRolesstops re-reading teams thatsetFieldshas already resolved.Invalidation.
hasAnyRole()andinAnyTeam()used to read the hierarchy from the database onevery evaluation and now answer from the summary in
USER_POLICIES_CACHE, so the writes that changeit have to reach every pod: a team, role or policy message drops the policy cache rather than only
the user contexts, and a user message drops that user's entry.
TeamRepositoryalso invalidates ondelete and on rename, neither of which passes through the updater that already did.
Alternatives rejected. (a) Gating
inheritedRoleson its own field name rather thandefaultRolesbreaks the re-entrancy but leaves the N+1 — still ~300 queries for a 100-group user,and it silently changes what
?fields=defaultRolesreturns. (b) Sharing the resolved closure withina single read would remove roughly a third of the remaining statements, but there is no per-request
context to hang it on; this repo deliberately removed a
ThreadLocalmemo fromEntityRepositoryfor exactly that reason (see
EntityRepositoryInheritanceParentTest).Compatibility. No schema, API or response changes.
inheritedRolesordering and content, andinherited domains, are unchanged.
Tests:
Use cases covered
a user in 2, and that number stays bounded by the hierarchy depth.
defaultRolesand a domain from a department twolevels above them; a role granted to a team, and a team moved under a new parent, both show up on
the next read.
inAnyTeam()/hasAnyRole()evaluated repeatedly — as a listing does, per rule per entity —resolve the subject's hierarchy once.
Organization.Unit tests
TeamHierarchyResolverTest.java(7 tests),TeamGraphFixture.java(shared in-memoryentity_relationshipstand-in so policy tests can describe a team graph without a database).SubjectCacheTest.java(+4: the repeated-rule-condition guard and three remoteinvalidation guards),
SubjectContextTest.java,RuleEvaluatorTest.java,CachedPermissionEvaluationTest.java,ElasticSearchRBACConditionEvaluatorTest.java,OpenSearchRBACConditionEvaluatorTest.java— rewired onto the fixture.mvn -P static-code-analysis test jacoco:report -pl openmetadata-service), line coverageon changed classes:
TeamHierarchyResolver93.0%,SubjectContext96.1%,SubjectCache77.0%.UserRepositoryandTeamRepositoryare exercised by the integrationtests rather than the unit suite; their diff is confined to the
setInheritedFields/fetchAndSetRoles/ invalidation paths covered below.openmetadata-serviceunit suite: 9757 tests, 1 failure —TaskWorkflowLifecycleResolverTest.workflowStartVariablesTolerateNullOptionalFields, confirmed tofail identically on unmodified
mainand unrelated to this change.Backend integration tests
openmetadata-integration-tests/.MultiTeamUserFanOutIT.java— the regression guard, which fails on unmodifiedmain(expected: <68> but was: <348>for a 2-group vs 30-group user) and also bounds the readso a return of the per-team walk fails loudly rather than merely getting slower;
TeamHierarchyInheritanceIT.java(3 tests) for the semantics and the post-write visibility;TeamHierarchyTestFactory.javafor the shared fixtures. Only the statement-count test is@Isolated— it decorates the application-wide SQL logger, which is why it cannot share a run —and the semantic tests are
@Execution(CONCURRENT).UserResourceIT,TeamResourceIT,PolicyResourceIT,RoleResourceIT,PermissionsResourceIT,DomainIsolationIT,UserTeamAssignmentPrivilegeIT,UserDefaultTeamAssignmentIT,UserImportPrivilegeEscalationIT,TeamDefaultPersonaIT:1006 tests, all green except
PolicyResourceIT.test_concurrentTagRenamesBothUpdatePolicyCondition, a pre-existing flakeunrelated to this change — it fails on a MySQL row-lock deadlock in
PolicyConditionUpdater(
SELECT … FOR UPDATEonpolicy_entity) and reproduces at the same rate on the commit thisbranch forked from (3 of 6 runs there, 4 of 8 here). Worth its own issue.
Ingestion integration tests
Playwright (UI) tests
Manual testing performed
suite does).
Organization → business unit → division → department → N groupsand a user in all Ngroups, for N = 1, 5, 10, 20, 40.
entity_relationshipstatements for one warmGET /v1/users/name/{name}?fields=teams,roles,domains,personas,defaultPersonausingSqlQueryCounter.forRequests. Onmain: 58 / 98 / 148 / 248 / 448. With this change: 38 at everyN (table above).
ancestry walks, one for inherited roles and one for inherited domains.
from this change and not the environment.
mvn spotless:checkis clean foropenmetadata-serviceandopenmetadata-integration-tests.UI screen recording / screenshots:
Not applicable — no UI changes.
Checklist:
Fixes <issue-number>: <short explanation>Fixes #<issue-number>above.MultiTeamUserFanOutITandTeamHierarchyResolverTestboth reference issue Major performance degradation for multi-group users #19778 in their class Javadoc for future reference.🤖 Generated with Claude Code
Open workspace in Conductor