Skip to content

Stop concurrent writers leaving a stale entity in the cache, and fix the revert/bump deadlock - #34077

Closed
harshach wants to merge 3 commits into
mainfrom
harshach/entity-cache-writer-order
Closed

harshach wants to merge 3 commits into
mainfrom
harshach/entity-cache-writer-order

Conversation

@harshach

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes the EventSubscriptionResourceIT.test_concurrentEnableDisableLeavesScheduleMatchingCommittedState flake on the Redis lane. This is a test fix, so there is no linked issue and the PR carries skip-pr-checks.

The test toggles an alert on and off from two threads and checks that the scheduler agrees with the row. When it failed (job), the scheduler was right: the database ended enabled and the job was scheduled. The test's GET, served from the entity cache, returned disabled. Two bugs combined:

  1. Writers stored their own copy of the entity in Redis after commit. Concurrent writers commit in one order but can finish their post-commit work in the other, so whichever finished last decided what the cache held. invalidateCachesAfterStore already documented this race as out of scope, because a version-guarded write needs a Redis read before every write. A version guard can't work in any case: a same-session revert moves both version and updatedAt backwards.
  2. Revert and version bump took their rows in opposite orders. A same-session revert rewrote the entity row, then deleted the version-history row. A version bump inserts the history row, then rewrites the entity row. The two requests deadlocked. Postgres broke the cycle after its one-second deadlock timeout, and the retry committed them in reverse order. That is what made the disable's copy land in Redis last.

Changes:

  • Writers only evict. After commit, the single create and update paths, the CSV import batches and postUpdateMany now evict the entity, as the bulk paths already did. Only readers load entities into the cache, from the database and under the existing write-epoch guard. Evictions commute, so the order writers finish in no longer matters. The JSON-capture ThreadLocal from Fixes 30008: Improve server startup and write-path latency #30009 existed only to feed the write-through, so it is removed along with its unit test.
  • Same lock order. A same-session revert now deletes the history row before rewriting the entity row, in both storeUpdate and storeUpdateWithOptimisticLocking.

Trade-off: the first read after a single create or update now loads from the database, not Redis. Bulk create and update already worked this way.

This overlaps with #33862, which also reorders invalidateCachesAfterStore, so whichever lands second needs a small merge. The two are complementary: #33862 fixes the reader-side L1 load race and Redis breaker recovery; this PR fixes writer-side ordering.

Type of change:

  • Bug fix

High-level design:

The cache moves to cache-aside: writers evict, readers populate.

  • Before: each write path stored its serialized entity in Redis after commit.
  • After: those paths evict the entity's by-id and by-name keys and the related relationship, bundle and lineage caches, as before. A reader that misses loads the row from the database and stores it, guarded by the write-epoch check.

Alternatives considered:

  • Version- or timestamp-guarded write-through. version and updatedAt are not monotonic under session consolidation.
  • Writing to Redis inside the transaction, ordered by the row lock. That puts a network call inside the DB transaction and needs compensation on rollback and deadlock retry.
  • Relying on EntityCacheRepair's re-eviction 500 ms after a write. It narrows the window but still serves the older state to reads inside it, which is exactly what the failing test did.

Rollout: no migration or configuration change.

Tests:

Use cases covered

  • Two writers commit in one order and finish their post-commit work in the other. Reads by id and by name serve the last committed write.
  • A same-session revert waits for the version-history row before locking the entity row, so it no longer deadlocks with a concurrent version bump.

Unit tests

  • None added. EntityRepositoryStorageJsonReuseTest is removed with the machinery it covered.
  • The org.openmetadata.service.jdbi3.** and org.openmetadata.service.cache.** unit tests pass: 849 tests.

Backend integration tests

  • openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/cache/EntityCacheWriteOrderIT.java (Redis profiles). It holds one writer's post-commit actions until a second writer has committed, then reads by id and by name.
    • On main: fails with expected: <later writer> but was: <earlier writer>.
    • With the fix: passes.
  • openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/EntityUpdateLockOrderIT.java (all profiles). It holds the version-history row as a concurrent bump would, and requires the chart row to stay lockable (FOR UPDATE NOWAIT) while the reverting update waits.
    • On main: fails, because the revert locked the chart row.
    • With the fix: passes.
  • Regression runs, locally:
    • Postgres + Elasticsearch + Redis (-Pcache-tests): 478 tests, 0 failures. Covers the new ITs, EventSubscriptionResourceIT, ContainerCacheCorrectnessIT, RelationshipCacheInvalidationIT, TagRenameCacheIT, OneTransactionFlushAtomicityIT, AsyncSearchIndexConsistencyIT, and ChartResourceIT including BaseEntityIT's Redis read-after-write tests.
    • MySQL + Elasticsearch + Redis: 250 tests, 0 failures. Covers the new ITs and EventSubscriptionResourceIT.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

  1. Traced the failing job's server log. The audit trail shows the enable committed last, and the scheduler re-read "enabled" from the database. Two post-commit Redis writes of different versions landed in the same millisecond, after a one-second deadlock between the revert and the bump.
  2. Ran both new ITs against unmodified main (both fail) and with the fix (both pass).
  3. mvn spotless:check on both changed modules.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation> — not applicable: a test fix has no issue and gets a descriptive title.
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above — not applicable: a test fix, labelled skip-pr-checks.
  • 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. (No schema changes.)
  • For UI changes: I attached a screen recording and/or screenshots above. (No UI changes.)
  • 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.

…a revert

A same-session update that returns an entity to its previous version
rewrote the entity row and then deleted that version's history row. A
version bump inserts the history row and then rewrites the entity row.
Taken in opposite orders, overlapping updates of one entity by the same
user deadlocked. Postgres broke the cycle only after its one-second
deadlock timeout, and the retry committed the two requests in the
reverse of their original order.

Both revert branches (storeUpdate and storeUpdateWithOptimisticLocking)
now delete the history row first, so the two paths take the rows in the
same order and simply queue.

EntityUpdateLockOrderIT holds the history row the way a concurrent bump
does and checks that the reverting update does not lock the entity row
while it waits.
…r's copy

After committing, every write path pushed its own serialized copy of the
entity into Redis. Concurrent writers commit in one order but can finish
that post-commit work in the other: the earlier committer is often still
dispatching lifecycle and search work when the later one is done. So the
cache could keep an older committed version until the next write or the
repair pass. EventSubscriptionResourceIT's concurrent enable/disable test
caught it on the Redis lane: the database held "enabled", the scheduler
agreed, and the cached GET returned "disabled".

A version guard cannot order the copies: a same-session revert moves both
the version and updatedAt backwards. Writers now only evict, as the bulk
paths already did, and only readers load entities into the cache, from
the database and under the write-epoch guard. Evictions commute, so the
order in which writers finish no longer matters.

The JSON-capture ThreadLocal existed only to feed the write-through, so
it goes too, with its unit test.

EntityCacheWriteOrderIT holds one writer's post-commit actions until a
second writer has committed, which replays the ordering on demand.
@harshach harshach added the skip-pr-checks Bypass PR metadata validation check label Sep 27, 2026
@harshach
harshach requested a review from a team as a code owner September 27, 2026 02:45
@harshach harshach added the skip-pr-checks Bypass PR metadata validation check label Sep 27, 2026
@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Sep 27, 2026
@github-actions

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit d9adc050274a0b2d9b3b09bbadaae605b3cfac01 in Playwright run 36289464721, attempt 1.

✅ 4602 passed · ❌ 0 failed · 🟡 3 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) 56m 1s

⏱️ Max setup 4m 53s · max shard execution 24m 33s · max shard-job elapsed before upload 27m 35s · reporting 1m 9s

🌐 122.00 requests/attempt · 2.24 app boots/UI scenario · 51.32% common-shard skew

Optimization targets still in progress:

  • Common shard skew was 51.32% (convergence target: at most 15%).
  • Application boot ratio was 2.24 per UI scenario (10975 boots / 4904 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard advanced-search-01 65 0 0 0 0 0
✅ Shard advanced-search-02 65 0 0 0 0 0
✅ Shard chromium-01 125 0 0 0 0 0
✅ Shard chromium-02 129 0 0 0 0 0
✅ Shard chromium-03 147 0 0 0 0 0
✅ Shard chromium-04 136 0 0 0 0 0
🟡 Shard chromium-05 138 0 1 0 0 0
✅ Shard chromium-06 166 0 0 0 0 0
✅ Shard chromium-07 148 0 0 0 0 0
✅ Shard chromium-08 123 0 0 0 0 0
✅ Shard chromium-09 143 0 0 0 0 0
✅ Shard chromium-10 148 0 0 0 0 0
✅ Shard chromium-11 185 0 0 0 0 0
✅ Shard chromium-12 159 0 0 0 0 0
✅ Shard chromium-13 137 0 0 0 0 0
✅ Shard chromium-14 155 0 0 0 0 0
✅ Shard chromium-15 147 0 0 0 0 0
✅ Shard chromium-16 163 0 0 0 0 0
🟡 Shard chromium-17 162 0 1 0 0 0
✅ Shard chromium-18 149 0 0 0 0 0
✅ Shard chromium-19 135 0 0 0 0 0
✅ Shard chromium-20 162 0 0 0 0 0
✅ Shard chromium-21 160 0 0 0 0 0
🟡 Shard chromium-22 149 0 1 0 0 0
✅ Shard chromium-23 131 0 0 0 0 0
✅ Shard chromium-24 170 0 0 0 0 0
✅ Shard chromium-25 169 0 0 1 0 0
✅ Shard chromium-26 135 0 0 0 0 0
✅ Shard chromium-27 153 0 0 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 35 0 0 0 0 0
✅ Shard import-export-02 86 0 0 0 0 0
✅ Shard import-export-03 29 0 0 0 0 0
✅ Shard ingestion-01 30 0 0 0 0 0
✅ Shard ingestion-02 45 0 0 0 0 0
✅ Shard ingestion-03 26 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
🟡 3 flaky test(s) (passed on retry)
  • Features/PersonaAIContext.spec.ts › configures every entity type, behavior, section, filter, and setting (shard chromium-05, 1 retry)
  • Pages/Teams.spec.ts › Verify breadcrumb navigation for a team with a dot in its name (shard chromium-17, 1 retry)
  • Flow/ConditionalPermissions.spec.ts › User with matchAnyTag permission can only view Messaging Services with the tag (shard chromium-22, 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

@gitar-bot

gitar-bot Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved

🟡 Medium risk · Repository-wide cache eviction and entity-history lock ordering change write behavior

Fixes concurrent writer cache staleness and revert/bump deadlock by switching to cache-aside eviction for writers and reordering lock acquisition in same-session reverts. Adds two integration tests demonstrating the fixes; all 849 unit tests and 728 regression integration tests pass.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

Options

Display: compact → Counting what did not apply, without listing it.

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

@harshach harshach closed this Oct 13, 2026
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 skip-pr-checks Bypass PR metadata validation check

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant