Repository navigation
Fixes #33861: Stop the entity cache serving entities older than a completed write - #33862
Conversation
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
✅ Playwright Results — workflow succeededValidated commit ✅ 4635 passed · ❌ 0 failed · 🟡 4 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) 34m 56s ⏱️ Max setup 4m 57s · max shard execution 19m 55s · max shard-job elapsed before upload 23m 15s · reporting 18s 🌐 227.36 requests/attempt · 2.19 app boots/UI scenario · 43.18% common-shard skew Optimization targets still in progress:
🟡 4 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 |
manerow
left a comment
There was a problem hiding this comment.
Requesting changes for the Redis recovery issue flagged inline.
🚦 Removed from the merge queue —
|
CACHE_WITH_ID and CACHE_WITH_NAME were Guava LoadingCaches, whose invalidate() is a no-op while a load for the key is in flight. A reader that loaded the pre-commit row stored it after the writer's post-commit eviction and served it until EntityCacheRepair evicted again 500 ms later. That is the Redis-lane test_sdkOnlyAsyncOperations failure: restore, then GET returns 404. - Build both caches with Caffeine, whose invalidate() waits for the in-flight load and discards what it read. - In invalidateCachesAfterStore, evict L1 after the Redis delete and write-through, so a read in between cannot reload the old Redis copy into L1. - find and findByName catch the loader's exceptions directly, since Caffeine does not wrap them. Only loader failures are handled there, as before. - COUNT_CACHE becomes a plain Guava Cache; its loader only threw. Part of #33861
While RedisCacheProvider was unavailable it skipped writes and deletes silently, and a failed command was only logged. Redis kept the value from before them for up to the entity TTL (1 h by default) and served it to every server once the circuit breaker closed. - Record the keys of writes skipped while unavailable or whose command failed. Tracking is bounded at 20,000 keys; the rest are counted and keep today's TTL behavior. - Each health check deletes them with per-key pipelined UNLINKs: before it reports Redis healthy again, and once more right after the recovery flip. - CachedEntityDao logs a skipped write as skipped instead of "Successfully wrote". Part of #33861
- Record a write skipped while Redis is down under stateLock, which the recovery flip also takes. Every skipped key is then recorded before recovery becomes visible, and the post-flip cleanup deletes it. - Serialize UnconfirmedWrites admission so concurrent writers cannot push the map past its limit. - Add trySet and tryHset, which report whether Redis applied the write, and log the entity write-through from that result instead of from provider availability. They are default methods on CacheProvider, so other implementations keep compiling. - Run the in-flight eviction test on the production cache builder with no mocks, and the ordering test on a real CachedEntityDao over an in-memory provider. Part of #33861
Back its value and hash maps with size-capped Caffeine caches so the fixture follows the bounded-cache rule even when reused with large inputs. Part of #33861
Recovery cleanup holds stateLock across the UNLINK round trip so steady writes cannot hold off recovery. As a monitor, every virtual thread that queued behind it (an L1 miss fills Redis through trySet) kept its carrier on JDK 21, stalling the virtual-thread scheduler for the round trip, up to ten command timeouts. A ReentrantLock gives the same exclusion and parks them. See ADR:2026-10-14-cache-misses-that-do-io-load-outside-the-cache-lock. Tests: four times as many virtual-thread writers as carriers all start while cleanup holds the lock (fails on the monitor), and the review's repro, a writer that never stops while health checks run, recovers on the third check (fails on e1572fd's provider).
Code Review ✅ Approved 2 closed / 2 findings🟡 Medium risk · Redis recovery cleanup and entity-cache epoch invalidation affect cross-server cache consistency; synchronization mistakes could expose stale entities or evict current cache state. Adds a second epoch bump and post-delete L1 eviction on entity writes, plus tracked Redis key deletion during circuit-breaker recovery, so readers can no longer serve entities older than a completed write. Failed Redis writes no longer log as successful, and cleanup no longer stalls Redis operations while the provider is available. No open issues found. ✅ 2 closed✅ Quality: Failed Redis writes still log "Successfully wrote"
✅ Performance: Cleanup under stateLock stalls every Redis op while provider is available
VerificationRules No rules evaluated Functional validation Not enabledAuto-approval Not enabledFor more verification details, comment OptionsDisplay: compact → Showing compact verification results. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
Describe your changes:
Fixes #33861
The entity cache could return an entity older than a write that had already returned. There were two causes, both on
main. The first one is behind the intermittentBaseEntityIT.test_sdkOnlyAsyncOperationsfailure on the Redis IT lane (restore, thenGET→ 404).1. In-JVM entity cache (
EntityRepository.CACHE_WITH_ID/CACHE_WITH_NAME)EntityCacheRepairevicted again 500 ms later.loadOutsideCacheLock, Fixes #35428: Stop cache-miss loads pinning virtual threads #35429). It reads the write epoch, loads,puts, then re-checks the epoch and evicts if it moved. This PR builds on that. Its earlier switch of L1 from Guava to Caffeine is gone: it depended on a loadingget, which pins virtual threads (ADR:2026-10-14-cache-misses-that-do-io-load-outside-the-cache-lock).EntityUpdater.invalidateCachesAfterStoreevicts L1 after Redis eviction, closing the window in which a reader could reload stale Redis JSON into L1. Main's eviction-only writer behavior is preserved: only readers repopulate Redis from the database.invalidateCachesAfterStoreand the deferred drain,evictCommittedWrites) bump the write epochs a second time, just before the L1 eviction. A reader that read its epoch after the first bump and fetched the stale Redis copy before the delete could otherwiseputthat copy after the L1 eviction and still pass its epoch re-check.2. Redis after the circuit breaker recovers
RedisCacheProviderremembers the keys of writes it skipped while unavailable, or whose command failed.ReentrantLock, not a monitor: cleanup holds it across a Redis round trip, and on JDK 21 a virtual thread waiting for a monitor keeps its carrier thread.CachedEntityDaonow logs cache fills from their real outcome. It used to log "Successfully wrote entity to Redis" for writes the provider had dropped or that had failed.trySet/tryHsetreport whether Redis applied the write.CacheProvider, so other implementations, including a Collate test fake, keep compiling.RedisCacheProviderimplements them exactly.Type of change:
High-level design:
Why a second epoch bump, for L1. With loads outside the cache lock, an eviction doesn't wait for a load in flight. A stale copy is dropped only if the epoch moves between the reader's first epoch read and its re-check after the
put.AtomicLongincrement.Why delete instead of hiding reads, for Redis.
CredentialTokenState's write-then-verify pattern.mget, so a clustered endpoint doesn't reject them with CROSSSLOT.The L1 and Redis fixes address independent stale-read paths.
Tests:
Use cases covered
e1572fd2643.Unit tests
EntityCacheLoadRaceTest: realCachedEntityDaoover an in-memory provider. The ordering test checks that L1 is evicted after Redis. The two slow-miss tests runloadOutsideCacheLockon a second thread, latched to fetch before the delete andputafter the write returns. They fail without the second epoch bump.UnconfirmedWritesTest, including a concurrency test for the key limitRedisCacheProviderUnconfirmedWritesTest(Testcontainersredis:7-alpine), including the new write-outcome resultsInMemoryCacheProvider, a map-backed test fakemain's code and pass with this change.cache,jdbi3andsecuritypackages passed (155 classes, 1,596 tests). Updated validation is listed below.EntityRepositoryRestoreTest,EntityRepositoryStorageJsonReuseTestRedisCacheProviderStateMachineTest,CachedEntityDaoAliasEvictionTestListCountCacheTest,BundleWarmupBatcherTest,EntityCacheBypassTestCachedPermissionEvaluationTest,SubjectContextTest,SubjectCacheTestTaskResourceContextTest,TeamHierarchyResolverTest,RuleEvaluatorTestMigrationUtilDataConsumerPolicyCacheTest(v200, v203)Validation after merging main (2026-10-15)
c4f204aa04c. The only conflict wasEntityRepository.find/findByNameagainst Fixes #35428: Stop cache-miss loads pinning virtual threads #35429. Main'sloadOutsideCacheLockpath is kept as-is, and the Caffeine switch,COUNT_CACHEandfindexception-handling changes are dropped.stateLockis now aReentrantLock(c26cc0163e9). Thecachepackage passes, 57 tests including the 10 real-Redis ones. The two new Redis tests fail on the code they guard against.cache,jdbi3andsecurityunit-test packages: 218 classes, 2,340 tests, zero failures, zero errors, zero skips.Validation after merging main (2026-09-29)
b50905bd7e5; reviewed and validated heade1572fd2643.mvn -pl openmetadata-service spotless:apply spotless:checkpassed;git diff --checkpassed.Backend integration tests
cache-tests) covers this path throughtest_sdkOnlyAsyncOperations.-Pcache-tests): 85 tests, 0 failures, and no Caffeine errors in the server log. The run covered:cache/*ITclasses,EntityCacheInvalidationITandAuditLogResourceITtest_sdkOnlyAsyncOperationsfor DataContract, Table and GlossaryIngestion integration tests
Playwright (UI) tests
Manual testing performed
UI screen recording / screenshots:
Not applicable.
Checklist:
I have read the CONTRIBUTING document.
My PR title is
Fixes <issue-number>: <short explanation>My PR is linked to a GitHub issue via
Fixes #<issue-number>above.I have commented on my code, particularly in hard-to-understand areas.
For JSON Schema changes: I updated the migration scripts or explained why it is not needed.
For UI changes: I attached a screen recording and/or screenshots above.
I have added tests (unit / integration / Playwright as applicable) and listed them above.
I have added a test that covers the exact scenario we are fixing.
🤖 Generated with Claude Code


Confidence Score: 5/5
The PR appears safe to merge; the latest change fixes the credential-barrier cleanup issue without an established new failure.Summary
The PR closes stale entity-cache races and removes uncertain Redis values before recovery. The latest change protects credential barriers from that cleanup.
Diagram
%%{init: {'theme': 'neutral'}}%% flowchart TD A[Redis health check succeeds] --> B[Read tracked keys] B --> C{Credential key?} C -->|Yes| D[Keep credential state] C -->|No| E[Delete uncertain cached value] D --> F[Forget completed tracking batch] E --> F F --> G{Recovery threshold reached and no pending keys?} G -->|Yes| H[Enable Redis reads] G -->|No| I[Wait for another health check]Reviews (6) · Last reviewed commit: "fix(cache): preserve credential barriers..." · Reviewed by Greptile