Repository navigation
Fixes #33711: publish the lifecycle handler list as an immutable snapshot - #33712
Conversation
…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.
❌ PR checklist incompleteThis 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 |
Code Review ✅ No issues found🟡 Medium risk · Concurrent lifecycle dispatch and handler replacement alter runtime indexing behavior. Fixes a race condition in OptionsDisplay: compact → Counting what did not apply, without listing it. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
✅ Playwright Results — workflow succeededValidated commit ✅ 4534 passed · ❌ 0 failed · 🟡 10 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) 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:
🟡 10 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 |
… 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.
Describe your changes:
Fixes #33711
EntityLifecycleEventDispatcherheld its registered handlers in a plainArrayList— mutated undersynchronized(registerHandler/unregisterHandler) but read with no synchronization at all on the dispatch path (getApplicableHandlers,getHandlers,getHandlerCount).ArrayList#removeIf→shiftTailOverGapdecrementssizefirst and then writesnullinto 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:VectorEmbeddingHandleris 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
volatileimmutable 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-registersSearchIndexHandler, andSystemRepository.retryInitAndReportError→initializeVectorSearchService()→OpenSearch/ElasticSearchVectorService.initre-registersVectorEmbeddingHandlerfrom the settings-validation API while requests are in flight.Type of change:
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
volatileimmutable snapshot overCopyOnWriteArrayList. Both make reads safe, but COWAL'saddandsortare two separate copy-on-write publishes, so a reader can briefly observe the list out of priority order. Handler priority is load-bearing here (SearchIndexHandler10 →DomainSyncHandler50 →VectorEmbeddingHandler200), 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
SearchRepositoryrebuild, vector-service re-init) never leaves a window in which an entity write sees no handler under that name.Unit tests
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'sgetSupportedEntityTypes(), unregisters the tail handler, then releases. Fails onmainwith the exact production stack above; passes with this change.testReplaceHandlerSwapsTheInstanceHeldUnderOneName,testReplaceHandlerRegistersWhenNoneIsHeldUnderThatName,testReplaceNullHandlerIsIgnored— cover the newreplaceHandlerAPI.mvn jacoco:prepare-agent test jacoco:report): 100% line coverage on every changed method —registerHandler15/15,replaceHandler12/12,unregisterHandler6/6,publishSorted3/3,clearHandlers2/2,getHandlers1/1,getApplicableHandlers3/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:
EntityLifecycleEventDispatcherTestSearchIndexHandlerTestOrderedLaneExecutorTest/EntityLifecyclePostCommitTestSearchRepositoryBehaviorTestorg.openmetadata.service.search.vector.**org.openmetadata.service.events.subscription/scheduled.**mvn spotless:applyclean;openmetadata-integration-teststest-compiles.Backend integration tests
openmetadata-integration-tests/.../PatchTableEmbeddingIT.java— removed its manualunregisterHandler("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 byvectorServiceInitialized, a second run left the handler unregistered for the rest of the JVM.Ingestion integration tests
Playwright (UI) tests
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:
mainwith the byte-identical production stack trace (getApplicableHandlers$13→ArrayListSpliterator.forEachRemaining).UI screen recording / screenshots:
Not applicable — no UI changes.
Checklist:
Fixes <issue-number>: <short explanation>Fixes #<issue-number>above.handlersfield carries a comment explaining why it must never be mutated in place, so the next reader does not "simplify" it back to anArrayList.🤖 Generated with Claude Code
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.
ArrayListstate.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]Reviews (1) · Last reviewed commit: "test: reference issue #33711 in the disp..."