Skip to content

fix(cache): a rolled-back transaction evicts the cache keys it wrote - #35722

Merged
pmbrull merged 5 commits into
mainfrom
pmbrull/pr-35672-testing
Oct 19, 2026
Merged

pmbrull merged 5 commits into
mainfrom
pmbrull/pr-35672-testing

Conversation

@pmbrull

@pmbrull pmbrull commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes the OntologyPropertyResourceIT and OntologyConceptResourceIT nativeDefinitionIriSurvivesUpdatesAndRestoration failures on the PostgreSQL + Elasticsearch + Redis lane. That lane has been red on main since #35672 (push run), and it reproduced in #35666's queue run (39214030862).

Root cause. The bug is in the cache platform, not the ontology code:

  1. A PUT on a soft-deleted ontology definition restores it inside executeInTransaction. The restore evicts L1 at once and defers the Redis eviction to the commit.
  2. OntologyEntityRepository.useRestoredRevision reads the definition back. L1 misses, so the loader reads the uncommitted restored row and caches it in L1 and Redis. The write epoch moved before that read started, so the race guard lets it through.
  3. The immutable-IRI check rejects the edit with a 400, and the database rolls back.
  4. DeferralScope.clear() discarded the deferred keys. Both caches kept the restored row until the 500 ms repair or the TTL, and GET ?include=deleted filtered it out as not deleted and answered 404.

The CI log shows the sequence: Restoring the ontologyProperty …, then CACHE: Writing entity to Redis … JSON length: 1731 (the restored row), then the 404.

ContextMemory conflict decisions hit the same failure in #35329 and fixed it only for themselves (ADR:2026-10-13-a-memory-conflict-opens-a-review-task-and-approving-it-supersedes-the-disputed-memory).

Fix in EntityRepository.DeferralScope:

  • A transaction that does not commit now evicts the keys its writes recorded instead of discarding them. It does exactly what a commit does: bumps the write epochs, sends one DEL, evicts L1 and the derived caches, and re-arms the repair.
  • A deadlock replay keeps the abandoned attempt's keys, so the final commit or rollback evicts them too.

Evicting is always safe, because the next read loads the committed row. The rule is recorded in docs/decisions/2026-10-19-a-rolled-back-transaction-evicts-the-cache-keys-it-wrote.md. The ContextMemory decision's own eviction from #35329 is now redundant. The second commit removes it and amends that decision record, so ContextMemoryConflictReviewIT now guards the platform rule. It also corrects comments that still described the cache collector as cleared per attempt and drained only after commit.

Type of change:

  • Bug fix

High-level design:

Not applicable: a small fix of two Java files plus a decision record.

Tests:

Use cases covered

  • A PUT that restores a soft-deleted ontology concept or property and is then rejected leaves the definition readable as deleted, with the Redis cache on: GET ?include=deleted returns 200 with the same version.
  • A unit of work that writes, reads its write back and then fails leaves neither L1 nor Redis serving the row the rollback undid.
  • The same holds after a deadlock replay whose final attempt no longer writes that entity.

Unit tests

  • DeferredCacheInvalidationTest gets two new tests: aRolledBackTransactionEvictsTheRowAReaderCachedInsideIt and aDeadlockReplayEvictsTheRowItsAbandonedAttemptCached.
    • Both drive the real executeInTransaction boundary against an in-memory Redis.
    • Before the fix both failed with Redis must not keep … ==> expected: <0> but was: <1>. After it they pass.
  • 13 related classes, 166 tests, 0 failures: DeferredCacheInvalidationTest, DeadlockRetryTest, EntityCacheVirtualThreadTest, EntityLifecyclePostCommitTest, EntityRepositoryRestoreTest, RetryableBoundaryTest, TransactionRollbackTrackerTest, OntologyEntityDAOTest, OntologyHierarchyStorageTest, OntologyReleaseCaptureTest, ChangeRequestServiceTest, ChangeRequestLifecycleTest, RdfUpdaterTest.
  • After the self-review changes (1070452cb10): 9 classes, 145 tests, 0 failures: DeferredCacheInvalidationTest, MemoryConflictResolutionTest, MemoryConflictReviewTasksTest, MemoryConflictDecisionTest, ContextMemoryLifecycleTest, RetryableBoundaryTest, DeadlockRetryTest, EntityRepositoryRestoreTest, TransactionRollbackTrackerTest.
  • Coverage (JaCoCo): EntityRepository.DeferralScope has 93% line coverage (55/59) from DeferredCacheInvalidationTest alone. A whole-class figure for EntityRepository says nothing about this change.

Backend integration tests

  • Locally with -Pcache-tests (PostgreSQL + Elasticsearch + Redis, parallel lane):
    • Before the fix (0473a800496): both nativeDefinitionIriSurvivesUpdatesAndRestoration cases fail with ApiException (404) at BaseOntologyIT.java:164, as in CI.
    • After the fix (411cc9bf198): 452 tests, 0 failures, 60 skipped. Both target cases PASSED. The run also covered OntologyConceptResourceIT, OntologyPropertyResourceIT, ContextMemoryConflictReviewIT, RestoreHierarchyIT, EntityCacheInvalidationIT, UnitOfWorkRollbackIT, EntityTransactionBoundaryIT and every cache/*IT.
    • After the self-review changes (1070452cb10): ContextMemoryConflictReviewIT, ContextMemoryLifecycleIT, OntologyConceptResourceIT and OntologyPropertyResourceIT ran 465 tests with 0 failures and 59 skipped. aDecisionThatFailsPartWayLeavesBothMemoriesAsTheyWere and both nativeDefinitionIriSurvivesUpdatesAndRestoration cases PASSED.
  • make java_affected selects the full unit and IT suites, because EntityRepository is over the planner's cap. The full matrix ran in CI on this branch for 1070452cb10. The later commits (db9fbfb88b0, c0c8fb4e43c, e1fe2d60449) change only the decision records and comments. The first runs, for 411cc9bf198, were cancelled when the self-review changes landed.

Java test results: PASSED. These are CI runs on 1070452cb10, the last commit that changed code; the later commits change only comments and decision records.

Workflow Lanes Result
MySQL + Elasticsearch parallel; global-state 640; rdf 282; retry-queue 36; multi-node 24 every lane passed, 0 failures
PostgreSQL + OpenSearch parallel 18,107 (1,768 skipped); global-state 640; rdf 282; retry-queue 36; multi-node 24 every lane passed, 0 failures
PostgreSQL + Elasticsearch + Redis parallel; global-state 640; retry-queue 36; multi-node 24 every lane passed, 0 failures

GitHub cut off the MySQL + Elasticsearch and Redis parallel-lane logs before Maven's totals. Both jobs concluded success, and their logs show no failing test. Unit tests ran in PR CI on 1070452cb10 ("Test Report"): 13,520 tests, 0 failed, 1 skipped.

make java_affected_run --ci-run can't record these runs, because it requires them to have tested HEAD.

Ingestion integration tests

Not applicable: no ingestion changes.

Playwright (UI) tests

Not applicable: a backend-only cache fix.

Manual testing performed

None beyond the integration tests above, which drive the failing API sequence end to end against PostgreSQL, Elasticsearch and Redis.

UI screen recording:

Not applicable: a backend-only fix.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>. Not applicable: this is a test-failure fix, so it has a descriptive title and the skip-pr-checks label.
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above. Not applicable, for the same reason.
  • 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. Not applicable: no schema changes.
  • For a UI feature or feature task: as part of PR creation, I ran the PR build in Docker with sample data and embedded a verified GitHub-hosted recording plus build/health evidence above. Not applicable: backend-only.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • Self-review: I reviewed the final diff against REVIEW.md (the pr-checklist skill runs it) and fixed every 🔴 finding, or answered it on the line below.
    • Pass 1 on 411cc9bf198 found no 🔴. Fixed in 1070452cb10: the redundant ContextMemory eviction, whose Javadoc had become false, and the stale cache-collector comments.
    • Answered, not fixed: a read inside a transaction can still put the uncommitted row into L1 and Redis, where other readers see it until the transaction ends. This predates the PR and is recorded in the new ADR's consequences. Closing it means not caching reads of keys the open transaction wrote, which is a follow-up.
    • Pass 2 on 1070452cb10 found one 🔴: the decision record overclaimed. It said code never needs its own failure-path eviction, but inserts record no cache key and the authorization-cache eviction runs only on commit. db9fbfb88b0 scopes the record to the keys writes record (updates, restores, deletes) and names both exceptions. The code was unchanged.
    • Pass 2 answered, not fixed: a replayed attempt can read the row its abandoned attempt cached. That predates this PR and is recorded in the ADR with the in-transaction read window. Nothing that gates the merge runs the Redis lane (-Pcache-tests), so I ran the guards locally with it on both code commits (results above), and the Redis CI lane is dispatched below.
    • Pass 3 on db9fbfb88b0 found one 🔴, again in the record's wording: the ten types Redis never caches (UNCACHED_ENTITY_TYPES) and TaskRepository/TaskFormSchemaRepository, which update through the DAO, record no key either. c0c8fb4e43c lists them with inserts as cases whose code still evicts on its own failure path, and rewords six remaining comments that still said the cache collector drains only after commit. No code changed. Making the rule cover those types (record keys for every type, evict only L1 for uncached ones) is a possible follow-up; no caller hits it today.
    • Outside this diff, pass 3 also noted from reading the code that a deadlock replay of an ontology PUT that restores a definition could fail with a spurious 412, because useRestoredRevision mutates the shared original. It is not addressed here.
    • Pass 4 on c0c8fb4e43c found no 🔴. Fixed its 🟡 on the record's insert wording in e1fe2d60449, a one-line documentation change: an insert does record a by-id key through its relationships; its by-name entries are what survive a rollback.
    • Pass 4, answered: reads inside a transaction can still cache rows that same transaction wrote. One consequence is that a deadlock replay of a restore can find the abandoned attempt's restored copy and skip the restore. This predates this PR and is recorded in the ADR. The fix is to make reads of keys held in the open deferral map bypass the cache, which is a follow-up.
  • Decision check: this PR adds docs/decisions/2026-10-19-a-rolled-back-transaction-evicts-the-cache-keys-it-wrote.md.
  • I have added a test that covers the exact scenario we are fixing.

🤖 Generated with Claude Code


Summary by Gitar

  • Refactoring:
    • Removed the evictUncommitted rollback eviction from MemoryConflictResolution.writeTogether, since rolled-back transactions now evict their own keys
    • Amended the ContextMemory decision record to note the eviction now comes from every rolled-back transaction

This will update automatically on new commits.

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; the latest documentation change matches the code.

Summary

Rolled-back transactions now evict recorded cache keys instead of discarding them. Deadlock retries keep abandoned attempts’ keys for the final eviction.

  • Transactions now evict cache keys even when they roll back.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Transaction records cache keys] --> B{Transaction result}
  B -->|Deadlock retry| C[Keep keys from abandoned attempt]
  C --> A
  B -->|Commit| D[Run deferred commit actions]
  D --> E[Evict recorded cache keys]
  B -->|Rollback| F[Discard deferred commit actions]
  F --> E
Loading

Reviews (5) · Last reviewed commit: "docs(cache): inserts leave their by-name..." · Reviewed by Greptile

A read inside a transaction caches the uncommitted row it loads, and a
failed transaction discarded its deferred evictions, so L1 and Redis kept
serving the row the rollback undid until the repair or the TTL. A PUT that
restores a soft-deleted ontology definition and then rejects its changed
IRI left it cached as restored, so GET ?include=deleted answered 404 on the
PostgreSQL + Elasticsearch + Redis lane (OntologyConceptResourceIT and
OntologyPropertyResourceIT nativeDefinitionIriSurvivesUpdatesAndRestoration).

A transaction that does not commit now evicts the keys its writes recorded,
exactly like a commit, and a deadlock replay keeps the abandoned attempt's
keys so the final commit or rollback evicts them too.
@pmbrull
pmbrull requested a review from a team as a code owner October 19, 2026 09:47
@pmbrull
pmbrull requested a review from mohityadav766 October 19, 2026 09:47
@pmbrull pmbrull added the skip-pr-checks Bypass PR metadata validation check label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Oct 19, 2026
Every rolled-back transaction now evicts the keys it wrote, so the
ContextMemory conflict decision no longer needs its own eviction, and
ContextMemoryConflictReviewIT guards the platform rule instead. Also
correct the comments that still described the cache collector as cleared
per attempt and drained only after commit, and amend the memory-conflict
decision record.
Inserts record no cache key, and the post-commit actions that evict the
authorization caches still run only on commit, so the decision record no
longer claims a rollback undoes everything a commit would evict.
Types Redis never caches and repositories that update through the DAO
record no cache key, so the decision record lists them with inserts as
cases whose code still evicts on its own failure path. Also reword the
remaining comments that said the cache collector drains only after
commit.
@gitar-bot

gitar-bot Bot commented Oct 19, 2026

Copy link
Copy Markdown
Code Review ✅ Approved

🟡 Medium risk · Changing EntityRepository to evict recorded cache keys after rollback and retries could cause stale reads or excess cache reloads if key tracking is wrong.

Fixes cache eviction for rolled-back transactions so keys written inside a failed unit of work are evicted instead of discarded, resolving the nativeDefinitionIriSurvivesUpdatesAndRestoration failures in OntologyPropertyResourceIT and OntologyConceptResourceIT. No issues found.

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

@pmbrull
pmbrull added this pull request to the merge queue Oct 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-10-19T14:29:29Z)

Blocked the queue: playwright-summary

Failed Playwright tests:

  • Pages/Lineage/LineageInteraction.spec.ts › platform lineage is view only in every band

@pmbrull
pmbrull merged commit 33b7085 into main Oct 19, 2026
85 of 86 checks passed
@pmbrull
pmbrull deleted the pmbrull/pr-35672-testing branch October 19, 2026 14:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ingestion 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.

2 participants