Skip to content

Fixes #33861: Stop the entity cache serving entities older than a completed write - #33862

Merged
harshach merged 10 commits into
mainfrom
harshach/entity-cache-stale-reads
Oct 20, 2026
Merged

harshach merged 10 commits into
mainfrom
harshach/entity-cache-stale-reads

Conversation

@harshach

@harshach harshach commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

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 intermittent BaseEntityIT.test_sdkOnlyAsyncOperations failure on the Redis IT lane (restore, then GET → 404).

1. In-JVM entity cache (EntityRepository.CACHE_WITH_ID / CACHE_WITH_NAME)

  • A reader that loaded the pre-commit row could store it in L1 after the writer's post-commit eviction. It stayed there until EntityCacheRepair evicted again 500 ms later.
  • Main now loads L1 misses outside the cache lock (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 loading get, which pins virtual threads (ADR:2026-10-14-cache-misses-that-do-io-load-outside-the-cache-lock).
  • EntityUpdater.invalidateCachesAfterStore evicts 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.
  • Both post-commit eviction paths (invalidateCachesAfterStore and 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 otherwise put that copy after the L1 eviction and still pass its epoch re-check.

2. Redis after the circuit breaker recovers

  • RedisCacheProvider remembers the keys of writes it skipped while unavailable, or whose command failed.
    • Each health check deletes those keys before attempting recovery. Recovery checks that no tracked writes remain under the same state lock used to record skipped writes.
    • Before this, Redis served the value from before those writes to every server, for up to the entity TTL (1 h by default).
  • A write skipped during cleanup keeps the provider unavailable until the next health check deletes its key. This closes the gap where the previous two-pass cleanup exposed stale keys between the availability flip and the second cleanup. Late successful operations also cannot recover the provider while cleanup is pending.
  • Recovery cleanup and skipped/failed-write tracking share one lock, so steady traffic can't hold off recovery (review feedback). It is a 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.
  • CachedEntityDao now 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.
    • New trySet / tryHset report whether Redis applied the write.
    • They are default methods on CacheProvider, so other implementations, including a Collate test fake, keep compiling. RedisCacheProvider implements them exactly.

Type of change:

  • Bug fix

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.

  • The first bump, before the Redis delete, catches readers that started before it. It also guards the loader's own Redis fill.
  • A reader that starts after the first bump, but reaches Redis before the delete, sees no further move unless the writer bumps again. So the writer bumps once more after the delete, just before evicting L1.
  • Each bump is a per-entity AtomicLong increment.

Why delete instead of hiding reads, for Redis.

  • Everything the provider stores treats a miss as "reload from the source of truth", including the credential-token snapshot. So deleting a key whose last write may be lost is always safe.
  • Masking reads of those keys would have broken CredentialTokenState's write-then-verify pattern.
  • The tracking is bounded at 20,000 keys, and admission is serialized so concurrent writers can't overshoot it. Past that, keys are counted, logged at WARN, and keep today's behavior (their TTL).
  • A full keyspace purge on overflow was ruled out because sessions live under the same keyspace.
  • Deletes are pipelined per key, like 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

  • A read racing a restore can't leave the soft-deleted entity in L1 once the restore has returned.
  • A miss that fetched the stale Redis copy just before the post-commit delete can't keep it in L1, on both the direct and the deferred (drain) eviction paths.
  • A write skipped while the breaker is open does not resurface after recovery. This runs against real Redis, with the container paused to trip the breaker.
  • The key of a write that failed while Redis was healthy is deleted by the next health check.
  • Redis recovers on the third health check while a writer keeps writing throughout, which is the review's repro. This fails on the provider at e1572fd2643.
  • Virtual threads that wait for recovery cleanup don't hold carrier threads: four times as many writers as carriers all start while cleanup holds the lock. This fails with a monitor.

Unit tests

  • I added unit tests for the new/changed logic.
  • Files added:
    • EntityCacheLoadRaceTest: real CachedEntityDao over an in-memory provider. The ordering test checks that L1 is evicted after Redis. The two slow-miss tests run loadOutsideCacheLock on a second thread, latched to fetch before the delete and put after the write returns. They fail without the second epoch bump.
    • UnconfirmedWritesTest, including a concurrency test for the key limit
    • RedisCacheProviderUnconfirmedWritesTest (Testcontainers redis:7-alpine), including the new write-outcome results
    • InMemoryCacheProvider, a map-backed test fake
  • The four race and recovery tests fail on main's code and pass with this change.
  • Before the main merge, every unit test in the cache, jdbi3 and security packages passed (155 classes, 1,596 tests). Updated validation is listed below.
  • Pre-merge cache-related validation included:
    • EntityRepositoryRestoreTest, EntityRepositoryStorageJsonReuseTest
    • RedisCacheProviderStateMachineTest, CachedEntityDaoAliasEvictionTest
    • ListCountCacheTest, BundleWarmupBatcherTest, EntityCacheBypassTest
    • CachedPermissionEvaluationTest, SubjectContextTest, SubjectCacheTest
    • TaskResourceContextTest, TeamHierarchyResolverTest, RuleEvaluatorTest
    • MigrationUtilDataConsumerPolicyCacheTest (v200, v203)

Validation after merging main (2026-10-15)

  • Merged main at c4f204aa04c. The only conflict was EntityRepository.find / findByName against Fixes #35428: Stop cache-miss loads pinning virtual threads #35429. Main's loadOutsideCacheLock path is kept as-is, and the Caffeine switch, COUNT_CACHE and find exception-handling changes are dropped.
  • The two new slow-miss tests fail with the second epoch bump removed and pass with it.
  • stateLock is now a ReentrantLock (c26cc0163e9). The cache package passes, 57 tests including the 10 real-Redis ones. The two new Redis tests fail on the code they guard against.
  • cache, jdbi3 and security unit-test packages: 218 classes, 2,340 tests, zero failures, zero errors, zero skips.
  • The Redis IT lane and Playwright were not rerun locally; CI will validate the pushed head.

Validation after merging main (2026-09-29)

  • Merged main at b50905bd7e5; reviewed and validated head e1572fd2643.
  • Preserved main's eviction-only writers, deferred post-commit eviction, and fresh-read bypass behavior.
  • Updated the deferred-invalidation test to use Caffeine's API and strengthened the L1 ordering test to cover both ID/name keys and ensure writers leave Redis entries evicted.
  • Added state-machine and real-Redis regressions for recovery with pending skipped writes. Both failed before the recovery fix and passed afterward.
  • Backend package build and cache/repository/security tests: 1,759 tests, zero failures, zero errors, zero skips (the cache memory benchmark was excluded).
  • mvn -pl openmetadata-service spotless:apply spotless:check passed; git diff --check passed.
  • The full server integration and Playwright suites were not rerun locally after this merge; updated CI will validate the pushed head.

Backend integration tests

  • Not applicable (no backend API changes). The Redis IT lane (cache-tests) covers this path through test_sdkOnlyAsyncOperations.
  • Before the main merge, ran locally against a real server with Postgres, Elasticsearch and Redis (-Pcache-tests): 85 tests, 0 failures, and no Caffeine errors in the server log. The run covered:
    • the cache/*IT classes, EntityCacheInvalidationIT and AuditLogResourceIT
    • test_sdkOnlyAsyncOperations for DataContract, Table and Glossary

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

  1. Diagnosed from the failing Redis-lane run of Reapply #30896: Complete Metrics hierarchy and details #32335, then from an instrumented local run of the full Redis lane. The local run also reproduced cause 2.

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

RetriggerView in GreptileConfidence 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.

  • Entity reads no longer leave an older copy in the in-JVM cache after a write.
  • Redis clears keys with missed writes before it lets cache reads resume.

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]
Loading

Reviews (6) · Last reviewed commit: "fix(cache): preserve credential barriers..." · Reviewed by Greptile

@harshach
harshach requested a review from a team as a code owner September 23, 2026 07:17
@harshach harshach added safe to test Add this label to run secure Github workflows on PRs backend labels Sep 23, 2026
@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit e1572fd2643732c2154b3064725ad220e745a350 in Playwright run 36637955926, attempt 1.

✅ 4635 passed · ❌ 0 failed · 🟡 4 flaky · ⏭️ 1 skipped · 🧰 0 lifecycle flaky

Performance

Blocking 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:

  • Common shard skew was 43.18% (convergence target: at most 15%).
  • Browser traffic was 227.36 requests per attempt (convergence target: fewer than 200).
  • Application boot ratio was 2.19 per UI scenario (10804 boots / 4925 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard advanced-search-01 67 0 0 0 0 0
✅ Shard advanced-search-02 63 0 0 0 0 0
🟡 Shard chromium-01 112 0 1 0 0 0
✅ Shard chromium-02 152 0 0 0 0 0
✅ Shard chromium-03 138 0 0 0 0 0
🟡 Shard chromium-04 136 0 1 0 0 0
✅ Shard chromium-05 147 0 0 0 0 0
✅ Shard chromium-06 124 0 0 0 0 0
✅ Shard chromium-07 185 0 0 0 0 0
✅ Shard chromium-08 157 0 0 0 0 0
✅ Shard chromium-09 125 0 0 0 0 0
✅ Shard chromium-10 151 0 0 0 0 0
✅ Shard chromium-11 173 0 0 0 0 0
✅ Shard chromium-12 163 0 0 0 0 0
✅ Shard chromium-13 159 0 0 1 0 0
✅ Shard chromium-14 141 0 0 0 0 0
✅ Shard chromium-15 150 0 0 0 0 0
🟡 Shard chromium-16 139 0 1 0 0 0
✅ Shard chromium-17 159 0 0 0 0 0
✅ Shard chromium-18 156 0 0 0 0 0
✅ Shard chromium-19 176 0 0 0 0 0
✅ Shard chromium-20 151 0 0 0 0 0
✅ Shard chromium-21 159 0 0 0 0 0
✅ Shard chromium-22 163 0 0 0 0 0
✅ Shard chromium-23 139 0 0 0 0 0
✅ Shard chromium-24 142 0 0 0 0 0
✅ Shard chromium-25 154 0 0 0 0 0
✅ Shard chromium-26 130 0 0 0 0 0
🟡 Shard chromium-27 182 0 1 0 0 0
✅ Shard data-asset-rules-01 65 0 0 0 0 0
✅ Shard domain-isolation-01 16 0 0 0 0 0
✅ Shard global-state-01 34 0 0 0 0 0
✅ Shard import-export-01 93 0 0 0 0 0
✅ Shard import-export-02 59 0 0 0 0 0
✅ Shard ingestion-01 22 0 0 0 0 0
✅ Shard ingestion-02 39 0 0 0 0 0
✅ Shard ingestion-03 32 0 0 0 0 0
✅ Shard reindex-01 41 0 0 0 0 0
✅ Shard search-01 12 0 0 0 0 0
✅ Shard search-rbac-01 29 0 0 0 0 0
🟡 4 flaky test(s) (passed on retry)
  • Features/ContextCenterArticlesFilters.spec.ts › sort options route to the correct data path (shard chromium-01, 1 retry)
  • Features/ContextCenterArticles.spec.ts › description: switching articles does not bleed unsaved content into next article (shard chromium-04, 1 retry)
  • Pages/Users.spec.ts › Admin soft & hard delete and restore user from profile page (shard chromium-16, 1 retry)
  • Features/AIMode/ProfileNotificationTab.spec.ts › Destination should work properly (shard chromium-27, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

@manerow manerow left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for the Redis recovery issue flagged inline.

@github-actions

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — merge_conflict (2026-10-17T01:03:13Z)

The entry left the queue before it was built, so no checks ran against it.

Conflicts with the latest main — rebase, then re-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).
@gitar-bot

gitar-bot Bot commented Oct 20, 2026

Copy link
Copy Markdown
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"

📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java:56-64 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java:93-103 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java:485-489
RedisCacheProvider.hset/set catch command failures themselves: they call recordWriteFailure and do not rethrow, so the catch in putBase/putByName never runs. The breaker only opens after 5 failures in 30 s. That means the first failures leave available() true, and this new branch logs "Successfully wrote entity to Redis" for writes that failed. When the failure that trips the breaker happens, the log says "skipped" instead of failed. So the log still doesn't tell you whether the write landed, which is the exact problem this change says it fixes. One fix is to have the provider report the outcome, for example by returning a boolean from hset/set or exposing a per-call result, and branch on that. The simpler option is to change the wording to "write issued" and leave outcomes to the provider's own error log.

✅ Performance: Cleanup under stateLock stalls every Redis op while provider is available

📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java:148-151 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java:157-169 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java:227-241 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java:359
healthCheck now runs deleteUnconfirmedWrites() inside synchronized (stateLock). That covers the case where the provider is still available: a write that failed below the breaker threshold leaves a tracked key, and the next health check pipelines UNLINKs while holding the lock. The wait is bounded only by awaitAll (≥1s, 3s at the default 300ms command timeout). Every successful get/set/hget on request threads calls recordSuccess() (e.g. line 359), which takes the same lock, and so does recordFailure. So one transient write failure makes all cache traffic on the server wait for the cleanup round-trip, and it waits longest when Redis is degraded, which is when writes fail. The new comment says only writers that find Redis unavailable wait, but the lock actually blocks the hot path. Fix: hold stateLock for cleanup and recovery only while !available. When the provider is available, run the cleanup outside the lock as before, because the recovery race does not apply in that state.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Entity cache can serve an entity older than a write that already returned

2 participants