Repository navigation
Fixes 33860: evict Redis L2 after commit, not inside the write transaction - #33866
Conversation
…tion A recursive soft-delete followed by a restore could silently leave part of the subtree soft-deleted, so a plain GET on a descendant 404'd long after the restore returned 200. The cause is invalidation ordering, not the restore cascade. restoreEntity runs inside executeInTransaction, and persistBulkUpdaters calls updateMany then invalidateMany while that transaction is still open. invalidateMany -> invalidate(T) -> invalidateCache(T) issued the Redis DEL inline, before the COMMIT. Any concurrent reader in that window took the resulting miss, read the not-yet-committed row (deleted=true) and re-populated the key with it. After the commit Redis kept serving deleted=true until TTL. The window is the whole cascade transaction - one database, three schemas, twelve tables in the failing run - not a nanosecond, which is why it was hit often enough to evict PRs from the merge queue. Both mechanisms needed to prevent this already existed and both stopped one layer short: - invalidateCacheForEntity(type, id, fqn) honours DEFERRED_CACHE_INVALIDATIONS and lets executeInTransaction drain it post-commit. invalidateCache(T) - the path every entity write actually takes - bypassed the scope and called the cache DAOs directly. Both now go through deferOrInvalidateRedisL2. - EntityCacheRepair exists specifically to backstop a racing loader's stale put, but only re-evicted the in-JVM Guava caches. It now re-evicts the Redis L2 too, and skips entirely when no Redis cache is configured. invalidateRedisL2ForEntity also picked up the reference and tag-usage variants that only the POJO path was dropping, so deferring loses no coverage - and invalidateCacheForEntity now matches its own javadoc claim of dropping "every cached variant". Guava L1 eviction stays inline: it is a local map operation, not a round trip, and keeping it immediate preserves read-your-write within the request. Fixes #33860 Co-Authored-By: Claude Opus 5 <[email protected]>
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
| private static void deferOrInvalidateRedisL2(String entityType, UUID id, String fqn) { | ||
| if (!isCacheableEntityType(entityType)) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
⚠️ Bug: Uncached types (user/domain/bot…) no longer publish cross-pod invalidation
invalidateCache(T) used to publish pub/sub for every entity type. It now goes through deferOrInvalidateRedisL2, which returns early for UNCACHED_ENTITY_TYPES (user, bot, domain, dataProduct, task, workflow*, testCaseResolutionStatus), so updates and deletes of those entities never reach peer pods. CACHE_WITH_ID/CACHE_WITH_NAME (Guava L1) still cache those types on every pod, so in a multi-pod Redis deployment the other pods keep serving stale users/domains/bots until TTL. Their remote Invalidatables also stop firing, e.g. the JwtFilter email→username cache for users and the not-found cache. UserRepository.invalidateTaskCacheForIds has a comment describing this exact gap and publishes manually to work around it. Fix: keep the isCacheableEntityType short-circuit for the Redis DELs, but still publish (deferred post-commit when a scope is open) for uncached types on the POJO write path. Or move the pubsub publish outside the cacheable gate.
Always fan out cross-pod invalidation; only gate the Redis DELs on cacheability.:
private static void deferOrInvalidateRedisL2(String entityType, UUID id, String fqn) {
if (!isCacheableEntityType(entityType)) {
// Peers still hold this type in Guava L1; tell them post-commit.
PostCommitActionQueue.runOrDefer(() -> publishInvalidation(entityType, id, fqn));
return;
}
Map<CacheInvalidationKey, CacheInvalidationKey> deferred = DEFERRED_CACHE_INVALIDATIONS.get();
if (deferred != null) {
recordCacheInvalidation(deferred, entityType, id, fqn);
} else {
invalidateRedisL2ForEntity(entityType, id, fqn);
}
}
Was this helpful? React with 👍 / 👎
| if (request.id() == null || CacheBundle.getCachedEntityDao() == null) { | ||
| return; | ||
| } | ||
| EntityRepository.invalidateRedisL2ForEntity(request.entityType(), request.id(), request.fqn()); |
There was a problem hiding this comment.
The 500 ms repair timer starts when invalidation is recorded inside the transaction, while the authoritative deferred invalidation runs only after commit. If a recursive restore lasts longer than 500 ms, this repair can evict Redis before commit. A concurrent reader can then load the old database state and write it back after the post-commit eviction, leaving the stale value in Redis. Start this repair from the post-commit path, or otherwise ensure its delay begins only after commit.
Knowledge Base Used: Metadata entity lifecycle
| if (request.id() == null || CacheBundle.getCachedEntityDao() == null) { | ||
| return; | ||
| } | ||
| EntityRepository.invalidateRedisL2ForEntity(request.entityType(), request.id(), request.fqn()); |
There was a problem hiding this comment.
The delayed Redis repair invalidates only request.fqn(), although rename requests also carry originalFqn. If a reader began loading the old name before the initial eviction and writes that entry back afterward, this delayed pass removes only the new-name key. The old alias then remains until TTL, so a lookup by the former FQN can return the renamed entity instead of not found. The Redis repair should invalidate the distinct original FQN too, as the existing L1 repair already does.
Knowledge Base Used: Metadata entity lifecycle
| if (request.id() == null || CacheBundle.getCachedEntityDao() == null) { | ||
| return; | ||
| } | ||
| EntityRepository.invalidateRedisL2ForEntity(request.entityType(), request.id(), request.fqn()); |
There was a problem hiding this comment.
Repair bypasses cacheability guard
This call bypasses deferOrInvalidateRedisL2 and its isCacheableEntityType guard. Because repair is scheduled before that guard, writes to deliberately uncached types such as tasks, bots, domains, and data products now perform delayed Redis deletions across every cache layer and publish cross-node invalidations. Large cascades therefore regain the Redis workload that the existing short-circuit avoids because it can push operations past their timeout budgets. Apply the same cacheability check to the delayed repair.
Knowledge Base Used: Metadata entity lifecycle
✅ Playwright Results — workflow succeededValidated commit ✅ 4569 passed · ❌ 0 failed · 🟡 18 flaky · ⏭️ 1 skipped · 🧰 0 lifecycle flaky PerformanceBlocking targets: ✅ met · Optimization targets: 🟡 in progress Shard-job maxima below are not the full workflow wall time; the linked run includes build, fixture, planning, and reporting. 🕒 Full workflow signal wall (to summary) 1h 1m 2s ⏱️ Max setup 5m 29s · max shard execution 23m 24s · max shard-job elapsed before upload 26m 56s · reporting 1m 3s 🌐 124.08 requests/attempt · 2.24 app boots/UI scenario · 41.88% common-shard skew Optimization targets still in progress:
🟡 18 flaky test(s) (passed on retry)
How to debug locally# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip # view trace |
Describe your changes:
Fixes #33860
A recursive soft-delete followed by a restore could silently leave part of the subtree soft-deleted,
so a plain
GETon a descendant 404'd long after the restore returned 200. In the failing run, 9 of12 tables came back and
sync_schema_2.sync_table_2_1did not — 253 ms after the restore committed,with no error logged anywhere.
The cause is invalidation ordering, not the restore cascade.
restoreEntityruns insideexecuteInTransaction, andpersistBulkUpdaterscallsupdateManytheninvalidateManywhile thattransaction is still open.
invalidateMany→invalidate(T)→invalidateCache(T)issued the RedisDELinline, before the COMMIT. Any concurrent reader in that window took the resulting miss,read the not-yet-committed row (
deleted=true) and re-populated the key with it. After the commitRedis kept serving
deleted=trueuntil TTL, and the read path turns that into a 404.The window is the whole cascade transaction — 1 database + 3 schemas + 12 tables — not a nanosecond,
which is why it was hit often enough to evict PRs from the merge queue.
Type of change:
High-level design:
Both mechanisms needed to prevent this already existed, and both stopped one layer short:
DEFERRED_CACHE_INVALIDATIONS—executeInTransactionopens the scope and drains it post-commitinvalidateCacheForEntity(type,id,fqn)honours it, butinvalidateCache(T)— the path every entity write actually takes — bypassed it and called the cache DAOs directlydeferOrInvalidateRedisL2EntityCacheRepair— delayed re-eviction, whose javadoc names this exact raceinvalidateRedisL2ForEntityalso picked up thereferenceandtagUsagevariants that only thePOJO path was dropping, so deferring loses no coverage — and it makes
invalidateCacheForEntitymatch its own javadoc claim of dropping "every cached variant".
Guava L1 eviction deliberately stays inline. It is a local map operation, not a round trip, and
keeping it immediate preserves read-your-write within the request.
Not changed: a handful of specialised paths still call the cache DAOs directly (the rename
cascade around
EntityRepository:11280-11465,ContainerRepository:834). They are outside thisbug's path; worth a follow-up sweep rather than widening this PR.
Tests:
Use cases covered
deployment under concurrent read load.
Unit tests
EntityRepositoryRestoreTest:invalidateCache_insideDeferralScope_holdsRedisEvictionUntilDrain— with a scope open the RedisDAO is untouched; after
drainCacheInvalidations()the base and by-name keys are evicted.invalidateCache_withoutDeferralScope_evictsRedisImmediately— guards against the fix silentlydisabling invalidation when there is no transaction to wait for.
Verified the test actually catches the bug by reverting
invalidateCacheto the inline call:and with the fix restored:
Wider unit sweep over the repository and cache packages
(
-Dtest='EntityRepository*Test,*Cache*Test'):Backend integration tests
RestoreHierarchyIT.syncRestore_restoresFullHierarchyandTableResourceIT>BaseEntityIT.test_sdkOnlyAsyncOperations— which should stop flaking on theRedis lane. I could not reproduce the race deterministically on a local single-threaded run, so
the CI Redis lane is the real signal here.
Ingestion integration tests
Playwright (UI) tests
Manual testing performed
Traced the failure end-to-end in the CI log for run 35744755756 (job 106804504501) by following the
failing table's UUID: created → cascade-soft-deleted (verified by the test's own
include=allread)→ database restore committed → 404. The 9 tables that returned 200 each logged
CACHE: Writing entity to Redisduring the assertion loop — cache misses, served from the DB andtherefore correct. The failing one logged no such write: it was a cache hit, and the hit was stale.
UI screen recording / screenshots:
Not applicable.
Checklist:
Fixes <issue-number>: <short explanation>Fixes #<issue-number>above.🤖 Generated with Claude Code
The PR is not safe to merge until delayed Redis repair is made post-commit-aware, covers the original rename FQN, and preserves uncached-entity exclusions.
Findings
Summary
This PR routes entity-write Redis invalidations through the existing post-commit deferral mechanism and extends delayed cache repair to Redis L2.
Diagram
sequenceDiagram participant W as Writer transaction participant R as Concurrent reader participant L2 as Redis L2 participant T as Delayed repair W->>T: Schedule repair (500 ms) T->>L2: Evict before long transaction commits R->>L2: Cache miss R->>W: Read pre-commit database state W-->>W: Commit W->>L2: Post-commit eviction R->>L2: Late put of stale state Note over T,L2: Repair already ran, so stale value survivesReviews (1) · Last reviewed commit: "fix(cache): evict Redis L2 after commit,..."