Skip to content

Fixes #33711: publish the lifecycle handler list as an immutable snapshot - #33712

Merged
sonika-shah merged 2 commits into
mainfrom
fix/33711-lifecycle-handler-snapshot
Sep 21, 2026
Merged

sonika-shah merged 2 commits into
mainfrom
fix/33711-lifecycle-handler-snapshot

Conversation

@mohityadav766

@mohityadav766 mohityadav766 commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #33711

EntityLifecycleEventDispatcher held its registered handlers in a plain ArrayList — mutated under synchronized (registerHandler / unregisterHandler) but read with no synchronization at all on the dispatch path (getApplicableHandlers, getHandlers, getHandlerCount).

ArrayList#removeIf → shiftTailOverGap decrements size first and then writes null into the vacated tail slot. A dispatch already walking the list has bound its stream spliterator fence to the pre-removal size, so it walks straight into the nulled slot and 500s the entity write:

Cannot invoke "…EntityLifecycleEventHandler.getSupportedEntityTypes()" because "handler" is null
  at EntityLifecycleEventDispatcher.lambda$getApplicableHandlers$13(…:358)
  at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1708)
  at EntityLifecycleEventDispatcher.onEntityCreated(…:122)

VectorEmbeddingHandler is priority 200, so it always sorts last — removing it always nulls exactly the slot a concurrent walker is about to read, which is why it is the handler that trips this.

I made the handler list a volatile immutable snapshot that the synchronized mutators replace wholesale. Readers get a consistent, fully sorted view with no locking, and add-plus-sort now publishes as one step so a dispatch can no longer observe a momentarily unsorted list either.

I also closed the second, quieter defect the same swap created: expressing a handover as unregister-then-register leaves an interval in which no handler of that name is registered, so an entity write landing in it is silently never indexed. replaceHandler() does the swap-by-name atomically, and the three production swap sites now use it.

This is not test-only. Handler registration is not startup-only — SearchRepository's constructor re-registers SearchIndexHandler, and SystemRepository.retryInitAndReportError → initializeVectorSearchService() → OpenSearch/ElasticSearchVectorService.init re-registers VectorEmbeddingHandler from the settings-validation API while requests are in flight.

Type of change:

  • Bug fix

High-level design:

N/A — small change (6 files, one class's internal data structure plus its three callers).

The one design note worth recording: I chose a volatile immutable snapshot over CopyOnWriteArrayList. Both make reads safe, but COWAL's add and sort are two separate copy-on-write publishes, so a reader can briefly observe the list out of priority order. Handler priority is load-bearing here (SearchIndexHandler 10 → DomainSyncHandler 50 → VectorEmbeddingHandler 200), so the snapshot swap — which publishes add-plus-sort as one step — is the stronger guarantee for the same read cost.

Iteration is now snapshot semantics: a handler unregistered during a dispatch still receives that in-flight event. That is the intended, defined behaviour and strictly better than the previous undefined read.

Tests:

Use cases covered

  • An entity write (create / update / delete / soft-delete) concurrent with a handler unregistration completes normally instead of failing with an NPE.
  • A handler handover (SearchRepository rebuild, vector-service re-init) never leaves a window in which an entity write sees no handler under that name.
  • A replacement handler is re-sorted to its own priority rather than inheriting the stale handler's slot.

Unit tests

  • I added unit tests for the new/changed logic.
  • Files updated: openmetadata-service/src/test/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventDispatcherTest.java (+4 tests, 25 → 28)
    • testUnregisterDuringDispatchNeverExposesANullHandler — the regression test. Deterministic, not a stress loop: it parks a dispatch mid-walk on a latch inside a handler's getSupportedEntityTypes(), unregisters the tail handler, then releases. Fails on main with the exact production stack above; passes with this change.
    • testReplaceHandlerSwapsTheInstanceHeldUnderOneName, testReplaceHandlerRegistersWhenNoneIsHeldUnderThatName, testReplaceNullHandlerIsIgnored — cover the new replaceHandler API.
  • Coverage (mvn jacoco:prepare-agent test jacoco:report): 100% line coverage on every changed method — registerHandler 15/15, replaceHandler 12/12, unregisterHandler 6/6, publishSorted 3/3, clearHandlers 2/2, getHandlers 1/1, getApplicableHandlers 3/3, <init> 4/4. Class total rose from 77.5% → 83.3% lines (65.6% → 70.0% branches); the remainder is pre-existing async/retry paths this PR does not touch.

Full suite run against the committed tree — 607 tests, 0 failures, 0 errors across 37 classes:

Suite Result
EntityLifecycleEventDispatcherTest 28/28
SearchIndexHandlerTest 23/23
OrderedLaneExecutorTest / EntityLifecyclePostCommitTest 9/9, 1/1
SearchRepositoryBehaviorTest 131/131
org.openmetadata.service.search.vector.** 259/259
org.openmetadata.service.events.subscription/scheduled.** 156/156

mvn spotless:apply clean; openmetadata-integration-tests test-compiles.

Backend integration tests

  • Not applicable (no API surface change). This fixes an intermittent failure of the existing IT suite rather than adding behaviour to test there.
  • Touched: openmetadata-integration-tests/.../PatchTableEmbeddingIT.java — removed its manual unregisterHandler("VectorEmbeddingHandler"). initializeVectorSearchService() now handles the handover atomically, and that manual call was the mutation tripping the race in the parallel IT lane. It was also actively wrong: guarded by vectorServiceInitialized, a second run left the handler unregistered for the rest of the JVM.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

No local Docker stack run — the failure is a thread interleaving, not a click path, so it is not reachable by hand. Verified instead by:

  1. Writing the regression test first and confirming it fails on unmodified main with the byte-identical production stack trace (getApplicableHandlers$13 → ArrayListSpliterator.forEachRemaining).
  2. Applying the fix and confirming the same test passes.
  3. Re-running the 607 tests above against the final committed tree.

UI screen recording / screenshots:

Not applicable — no UI changes.

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 — the handlers field carries a comment explaining why it must never be mutated in place, so the next reader does not "simplify" it back to an ArrayList.
  • For JSON Schema changes: N/A — no schema changes.
  • For UI changes: N/A — 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, referencing Entity writes intermittently 500 with an NPE: EntityLifecycleEventDispatcher reads its handler list unsynchronized #33711.

🤖 Generated with Claude Code

RetriggerConfidence Score: 5/5

The PR appears safe to merge, with the immutable snapshot and atomic replacement preserving current contracts while fixing the concurrent-dispatch race.

Summary

This PR makes lifecycle-handler reads concurrency-safe by publishing immutable, priority-sorted snapshots from synchronized mutators. It also introduces atomic same-name handler replacement and adopts it for search and vector-service handovers.

  • Prevents dispatch from observing partially mutated ArrayList state.
  • Preserves priority ordering as part of each atomic publication.
  • Eliminates unregister/register gaps during search and vector-handler replacement.
  • Adds deterministic coverage for concurrent unregistration and replacement semantics.
  • Removes the integration test’s now-unnecessary manual vector-handler unregistration.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Register, replace, or unregister] --> B[Synchronized mutator]
  B --> C[Copy current immutable snapshot]
  C --> D[Apply change and sort by priority]
  D --> E[Volatile publish with List.copyOf]
  E --> F[Concurrent dispatch reads one stable snapshot]
  F --> G[Handlers execute in priority order]
Loading

Reviews (1) · Last reviewed commit: "test: reference issue #33711 in the disp..."

…shot

EntityLifecycleEventDispatcher held its handlers in a plain ArrayList,
mutated under synchronized but read with no synchronization at all on
the dispatch path. ArrayList#removeIf decrements size and then nulls the
vacated tail slot, so a dispatch whose stream fence is already bound to
the pre-removal size reads that slot back as a null handler and fails
the entity write with an NPE on getSupportedEntityTypes(). Registration
is not startup-only -- a SearchRepository rebuild and vector-service
re-init both re-register handlers while requests are in flight -- so the
race is reachable in production, not only under parallel CI.

Hold the handlers in a volatile immutable snapshot that the synchronized
mutators replace wholesale. Readers get a consistent, fully sorted view
with no locking, and add-plus-sort now publishes as one step so a
dispatch can no longer observe a momentarily unsorted list either.

Also close the window that same swap opened: unregister-then-register
leaves an interval with no handler under that name, so an entity write
landing in it is silently never indexed. Add replaceHandler() for an
atomic swap-by-name and use it from SearchRepository and both vector
services. PatchTableEmbeddingIT's manual unregister is now redundant and
was the mutation tripping the race in the parallel IT lane.
@mohityadav766
mohityadav766 requested a review from a team as a code owner September 21, 2026 10:58
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

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

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 backend safe to test Add this label to run secure Github workflows on PRs labels Sep 21, 2026
@gitar-bot

gitar-bot Bot commented Sep 21, 2026

Copy link
Copy Markdown
Code Review ✅ No issues found

🟡 Medium risk · Concurrent lifecycle dispatch and handler replacement alter runtime indexing behavior.

Fixes a race condition in EntityLifecycleEventDispatcher where concurrent handler unregistration during entity dispatch could expose null references in the handler list, causing NPE 500s. Replaces the mutable ArrayList with a volatile immutable snapshot that publishes add-plus-sort atomically, and adds replaceHandler() to prevent transient windows where no handler is registered during handovers. Includes deterministic regression test and 100% line coverage on all changed methods; full test suite (607 tests) passes.

Review coverage

📋 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

@github-actions

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit 13e9f01a0199d30166588e143ec6fec5f9888b31 in Playwright run 35591559871, attempt 1.

✅ 4534 passed · ❌ 0 failed · 🟡 10 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) 54m 58s

⏱️ Max setup 4m 46s · max shard execution 22m 19s · max shard-job elapsed before upload 26m 3s · reporting 21s

🌐 223.47 requests/attempt · 2.23 app boots/UI scenario · 44.06% common-shard skew

Optimization targets still in progress:

  • Common shard skew was 44.06% (convergence target: at most 15%).
  • Browser traffic was 223.47 requests per attempt (convergence target: fewer than 200).
  • Application boot ratio was 2.23 per UI scenario (10809 boots / 4840 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard advanced-search-01 130 0 0 0 0 0
✅ Shard chromium-01 150 0 0 0 0 0
🟡 Shard chromium-02 169 0 1 0 0 0
✅ Shard chromium-03 153 0 0 0 0 0
🟡 Shard chromium-04 165 0 1 0 0 0
✅ Shard chromium-05 160 0 0 0 0 0
✅ Shard chromium-06 135 0 0 0 0 0
✅ Shard chromium-07 142 0 0 1 0 0
🟡 Shard chromium-08 169 0 1 0 0 0
✅ Shard chromium-09 181 0 0 0 0 0
🟡 Shard chromium-10 145 0 1 0 0 0
✅ Shard chromium-11 149 0 0 0 0 0
✅ Shard chromium-12 152 0 0 0 0 0
✅ Shard chromium-13 165 0 0 0 0 0
🟡 Shard chromium-14 168 0 2 0 0 0
✅ Shard chromium-15 136 0 0 0 0 0
✅ Shard chromium-16 154 0 0 0 0 0
✅ Shard chromium-17 165 0 0 0 0 0
✅ Shard chromium-18 147 0 0 0 0 0
✅ Shard chromium-19 199 0 0 0 0 0
✅ Shard chromium-20 173 0 0 0 0 0
🟡 Shard chromium-21 131 0 1 0 0 0
✅ Shard chromium-22 175 0 0 0 0 0
🟡 Shard chromium-23 145 0 2 0 0 0
✅ Shard chromium-24 155 0 0 0 0 0
🟡 Shard chromium-25 176 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 52 0 0 0 0 0
✅ Shard import-export-02 98 0 0 0 0 0
✅ Shard ingestion-01 50 0 0 0 0 0
✅ Shard ingestion-02 49 0 0 0 0 0
✅ Shard reindex-01 23 0 0 0 0 0
✅ Shard reindex-02 17 0 0 0 0 0
✅ Shard search-01 12 0 0 0 0 0
✅ Shard search-rbac-01 29 0 0 0 0 0
🟡 10 flaky test(s) (passed on retry)
  • Pages/DataProductAndSubdomains.spec.ts › Create data product via UI with description (shard chromium-02, 1 retry)
  • Pages/Tag.spec.ts › Verify Owner Add Delete (shard chromium-04, 1 retry)
  • Pages/ExplorePageRightPanel_KnowledgeCenter.spec.ts › Should remove user owner for knowledgeCenter (shard chromium-08, 1 retry)
  • Features/DataQuality/DataObservabilityGovernanceTab.spec.ts › clicking Data Observability tab loads DQ dashboard widgets (shard chromium-10, 1 retry)
  • Features/Glossary/GlossaryMutualExclusivityDataProductTree.spec.ts › ME-T01: Apply single ME glossary term and save Data Product (shard chromium-14, 1 retry)
  • Features/Glossary/GlossaryMutualExclusivityDataProductTree.spec.ts › ME-H01: ME glossary (top level) children render Radio with ME behavior (shard chromium-14, 1 retry)
  • Features/Tasks/DomainFiltering.spec.ts › switching domain triggers feed API refetch on entity page (shard chromium-21, 1 retry)
  • Features/ContextCenterArticles.spec.ts › Left hierarchy pagination and expand collapse actions work (shard chromium-23, 1 retry)
  • Features/MetricCustomUnitFlow.spec.ts › Should create metric and test unit of measurement updates (shard chromium-23, 1 retry)
  • Features/DomainTierCertificationVoting.spec.ts › DataProduct - Tier assign, update, and remove (shard chromium-25, 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

@mohityadav766 mohityadav766 self-assigned this Sep 21, 2026
@sonika-shah
sonika-shah added this pull request to the merge queue Sep 21, 2026
Merged via the queue into main with commit 1526d36 Sep 21, 2026
160 of 162 checks passed
@sonika-shah
sonika-shah deleted the fix/33711-lifecycle-handler-snapshot branch September 21, 2026 15:21
youngsofun pushed a commit to youngsofun/OpenMetadata that referenced this pull request Sep 22, 2026
… lane and make alert scheduling idempotent (open-metadata#33739)

* Fixes open-metadata#33738: keep multi-node suites out of the parallel lane

CsvExportMultiNodeIT boots extra full OpenMetadata servers inside the shared
test JVM. It is @tag("multi-node") and listed in integrationTests.multiNodeTests,
but unlike its three siblings it was never added to an isolated-tests <includes>
or a parallel-tests <excludes> list, so it also ran in the parallel lane next to
4 concurrent workers -- replacing process-wide singletons and joining the
clustered Quartz job store underneath every other suite in the fork. That is what
produced the two unrelated-looking merge-queue failures: the lifecycle dispatcher
NPE (mechanism since fixed by open-metadata#33712) and the Quartz "Unable to unschedule
trigger [...] while deleting job [...]" 500.

Add it to all 8 include and all 8 exclude lists, and repair the tag backstop that
should have caught the omission: excludedGroups sat inside systemPropertyVariables
where failsafe never reads it, a mistake the pom already documents for search-it
and ui-it. It is now a direct <configuration> child in every parallel-tests
execution, and all four multi-node classes carry @tag("multi-node"), so a future
one is excluded even if the filename lists are forgotten.

Also close the Quartz race itself, which is reachable outside tests -- every node
reinstalls every subscription on startup against one clustered job store, so a
rolling restart hits it. QuartzScheduler.deleteJob lists a job's triggers and then
unschedules them in separate transactions and throws when one is already gone,
which is the state being asked for rather than a failure. The enabled path now
writes the job and its trigger in a single transaction with replace=true instead
of delete-then-add, which also removes the window where the alert is unscheduled
at all; delete drops the trigger before the job and accepts a lost race once the
job is confirmed gone.

Finally, SessionMultiNodeCluster now refuses to start when it finds itself in a
fork configured for parallel execution, so this misconfiguration fails loudly in
the offending lane instead of corrupting a run whose symptoms surface later in an
unrelated test, and it tears down a node whose startup threw.

* Order alert scheduling against committed state, and stop the test swallowing failures

Addresses both review findings on open-metadata#33739.

Scheduler updates were still unordered. The schedule was driven by whichever
entity the caller happened to hold, so a disable that committed first but reached
the scheduler second deleted the job a later enable had just installed, leaving
the row enabled with no Quartz job -- the subscription looked active and silently
never fired again. The delete retry loop made it worse rather than better: it
re-deleted whatever occupied the key, so it hunted down the replacement.

syncScheduledState now takes a per-subscription lock (Guava Striped, bounded by
construction rather than a map that grows with the catalog), re-reads the
committed row inside it, and drives the schedule from that. The stale disable now
re-reads, sees enabled, and schedules instead of deleting; whichever request holds
the lock last observes the final committed state, so the schedule converges on it
regardless of arrival order. A peer node holds its own lock and can still commit
between this node's read and its write, so the row is read again after applying
and re-applied when it moved, bounded at three rounds. isSettled requires both
that the row has not moved and that the job store agrees with it, which also
covers a lost deleteJob race. That race now stops instead of retrying: deleteJob
can only fail once the trigger is already gone, meaning another writer installed a
pair since, and deleting that would undo work newer than ours.

reinstall no longer changes anything, so the two-argument addSubscriptionPublisher
is deprecated in favour of a one-argument overload and the internal callers move
across. The deprecated overload stays so downstream callers keep compiling.

The concurrency test accepted any exception whose rendered cause contained "(500)"
or "unschedule trigger", which let unrelated server errors pass, and because an
exception also aborted that worker's remaining toggles the test could pass without
exercising the workload. Failures now propagate from Future.get(); the single
collision this workload legitimately produces -- two toggles racing on one entity
version -- is retried in toggleEnabled on HTTP 409 only, read off the cause chain
via getStatusCode() rather than matched against text, since the SDK wraps the
transport failure and leaves statusCode at -1 on the wrapper. Retrying rather than
aborting also means every worker finishes its share, which the test now asserts.

test_concurrentEnableDisableLeavesScheduleMatchingCommittedState covers the
ordering: 20 rounds of a simultaneous enable and disable, asserting after each
that the schedule agrees with the committed row in both directions. Verified to
fail against the pre-fix scheduler ("Round 5: the row reads enabled but nothing is
scheduled for it") and to pass with it.

This branch was previously deployed

1 inactive deployment
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 writes intermittently 500 with an NPE: EntityLifecycleEventDispatcher reads its handler list unsynchronized

2 participants