forked from DSpace/DSpace
-
Notifications
You must be signed in to change notification settings - Fork 1
Fix flaky tests in IT pipeline #1321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
9bf258d
Fixed integration tests because they use to fail sometimes
milanmajchrak bb09815
test: stabilize flaky CI tests (Hibernate cleanup retry, Shibboleth a…
milanmajchrak 6e86590
test: fix flaky ITs at the source (live ORCID, Shibboleth config-relo…
milanmajchrak b6e300e
test: revert IT-env config-reload=false override
milanmajchrak 106de96
test: make Shibboleth auth-sequence override reload-safe (fix WWW-Aut…
milanmajchrak ead032f
test: add Hibernate concurrency monitor + CI upload to pinpoint @Afte…
milanmajchrak 0a88723
fix: don't close iterate() Hibernate stream from a finalize() (root c…
milanmajchrak 11c113b
fix: remove broken Context.finalize() that leaked finalizer-thread se…
milanmajchrak 0b2e9b7
test: remove flaky-CME diagnostic scaffolding and teardown retry (roo…
milanmajchrak 5375b50
revert: keep Context.finalize() (out of scope, not the CME cause)
milanmajchrak a30ca79
test: address review comments on flaky-test fix
milanmajchrak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
139 changes: 139 additions & 0 deletions
139
dspace-api/src/test/java/org/dspace/HibernateConcurrencyMonitor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| /** | ||
| * The contents of this file are subject to the license and copyright | ||
| * detailed in the LICENSE and NOTICE files at the root of the source | ||
| * tree and available online at | ||
| * | ||
| * http://www.dspace.org/license/ | ||
| */ | ||
| package org.dspace; | ||
|
|
||
| import java.io.File; | ||
| import java.io.PrintWriter; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| /** | ||
| * TEST DIAGNOSTIC (temporary) for the rare Hibernate {@code ConcurrentModificationException} thrown from | ||
| * {@code ResourceRegistryStandardImpl.releaseResources} during {@code @After} cleanup | ||
| * (see {@link AbstractIntegrationTestWithDatabase#destroy()}). | ||
| * | ||
| * <p>That CME provably requires a SECOND thread to mutate the test thread's per-session, non-thread-safe JDBC | ||
| * resource registry while the test thread commits/rolls back. A live thread-dump of a running IT JVM shows that | ||
| * NO legitimate background thread ever touches Hibernate (every persistent thread is Solr, HTTP-client, Jetty or | ||
| * a JVM thread). Therefore <b>any</b> non-test thread caught executing inside Hibernate JDBC / session code is, | ||
| * by definition, the culprit.</p> | ||
| * | ||
| * <p>This monitor is a JVM-wide background sampler. Every {@link #SAMPLE_INTERVAL_MS} ms it snapshots all thread | ||
| * stacks and records (de-duplicated) any non-test, non-monitor thread found inside | ||
| * {@code org.hibernate.resource.jdbc}, {@code org.hibernate.engine.jdbc} or {@code org.hibernate.internal.SessionImpl}. | ||
| * Records are flushed to {@code target/cme-dumps/} on a captured CME and at JVM shutdown. It is a pure observer: | ||
| * it never touches Hibernate, never throws into test code, and never changes behaviour. Delete once the culprit | ||
| * thread has been identified and fixed at its source.</p> | ||
| */ | ||
| public final class HibernateConcurrencyMonitor { | ||
|
|
||
| private static final long SAMPLE_INTERVAL_MS = 20; | ||
|
|
||
| /** Thread ids of legitimate test threads (the JUnit thread(s)) to ignore. */ | ||
| private static final Set<Long> TEST_THREAD_IDS = ConcurrentHashMap.newKeySet(); | ||
|
|
||
| /** De-duplicated culprit fingerprints: key -> formatted record. */ | ||
| private static final Map<String, String> CULPRITS = new ConcurrentHashMap<>(); | ||
|
|
||
| private static volatile boolean started; | ||
|
|
||
| private HibernateConcurrencyMonitor() { | ||
| } | ||
|
|
||
| /** Start the monitor exactly once per JVM (fork). Safe to call from every test's setUp. */ | ||
| public static synchronized void startOnce() { | ||
| if (started) { | ||
| return; | ||
| } | ||
| started = true; | ||
| Thread t = new Thread(HibernateConcurrencyMonitor::loop, "hibernate-concurrency-monitor"); | ||
| t.setDaemon(true); | ||
| t.start(); | ||
| Runtime.getRuntime().addShutdownHook(new Thread(() -> flush("jvm-shutdown"), "hibernate-concurrency-flush")); | ||
| } | ||
|
|
||
| /** Mark the current thread as a legitimate test thread, so its (normal) Hibernate use is ignored. */ | ||
| public static void markTestThread() { | ||
| TEST_THREAD_IDS.add(Thread.currentThread().getId()); | ||
| } | ||
|
|
||
| private static void loop() { | ||
| final long monitorId = Thread.currentThread().getId(); | ||
| while (true) { | ||
| try { | ||
| Map<Thread, StackTraceElement[]> all = Thread.getAllStackTraces(); | ||
| for (Map.Entry<Thread, StackTraceElement[]> e : all.entrySet()) { | ||
| Thread th = e.getKey(); | ||
| if (th.getId() == monitorId || TEST_THREAD_IDS.contains(th.getId())) { | ||
| continue; | ||
| } | ||
| if (touchesHibernateJdbc(e.getValue())) { | ||
| record(th, e.getValue()); | ||
| } | ||
| } | ||
| Thread.sleep(SAMPLE_INTERVAL_MS); | ||
| } catch (InterruptedException ie) { | ||
| return; | ||
| } catch (Throwable ignore) { | ||
| // A diagnostic must never die from a transient error (e.g. a thread terminating mid-snapshot). | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static boolean touchesHibernateJdbc(StackTraceElement[] stack) { | ||
| for (StackTraceElement f : stack) { | ||
| String c = f.getClassName(); | ||
| if (c.startsWith("org.hibernate.resource.jdbc") | ||
| || c.startsWith("org.hibernate.engine.jdbc") | ||
| || c.startsWith("org.hibernate.internal.SessionImpl")) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private static void record(Thread th, StackTraceElement[] stack) { | ||
| StringBuilder sb = new StringBuilder(); | ||
| int n = Math.min(stack.length, 25); | ||
| for (int i = 0; i < n; i++) { | ||
| sb.append("\tat ").append(stack[i]).append('\n'); | ||
| } | ||
| String stackText = sb.toString(); | ||
| String key = th.getName() + "|" + Integer.toHexString(stackText.hashCode()); | ||
| CULPRITS.putIfAbsent(key, "\"" + th.getName() + "\" id=" + th.getId() | ||
| + " daemon=" + th.isDaemon() + " state=" + th.getState() | ||
| + " group=" + (th.getThreadGroup() == null ? "?" : th.getThreadGroup().getName()) + "\n" + stackText); | ||
| } | ||
|
|
||
| /** Write all captured culprit fingerprints to target/cme-dumps/ (no-op if none were caught). */ | ||
| public static void flush(String reason) { | ||
| if (CULPRITS.isEmpty()) { | ||
| return; | ||
| } | ||
| try { | ||
| File dir = new File("target/cme-dumps"); | ||
| dir.mkdirs(); | ||
| File out = new File(dir, "hibernate-concurrency-" + System.currentTimeMillis() + "-" + reason + ".txt"); | ||
| try (PrintWriter pw = new PrintWriter(out, "UTF-8")) { | ||
| pw.println("===== Non-test threads caught INSIDE Hibernate JDBC / session code ====="); | ||
| pw.println("reason=" + reason + " distinctFingerprints=" + CULPRITS.size()); | ||
| pw.println("Baseline: NO legitimate background thread touches Hibernate, so each entry below is a"); | ||
| pw.println("suspect for the @After ConcurrentModificationException (concurrent access to the test"); | ||
| pw.println("thread's non-thread-safe per-session JDBC ResourceRegistry)."); | ||
| pw.println(); | ||
| for (String rec : CULPRITS.values()) { | ||
| pw.println(rec); | ||
| pw.println("------------------------------------------------------------"); | ||
| } | ||
| } | ||
| } catch (Exception ignore) { | ||
| // best-effort diagnostic | ||
| } | ||
| } | ||
| } |
64 changes: 64 additions & 0 deletions
64
dspace-api/src/test/java/org/dspace/core/AbstractHibernateDAOIteratorIT.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /** | ||
| * The contents of this file are subject to the license and copyright | ||
| * detailed in the LICENSE and NOTICE files at the root of the source | ||
| * tree and available online at | ||
| * | ||
| * http://www.dspace.org/license/ | ||
| */ | ||
| package org.dspace.core; | ||
|
|
||
| import static org.junit.Assert.assertNotNull; | ||
| import static org.junit.Assert.fail; | ||
|
|
||
| import java.util.Iterator; | ||
|
|
||
| import org.dspace.AbstractIntegrationTestWithDatabase; | ||
| import org.dspace.content.MetadataValue; | ||
| import org.dspace.content.factory.ContentServiceFactory; | ||
| import org.dspace.content.service.MetadataValueService; | ||
| import org.junit.Test; | ||
|
|
||
| /** | ||
| * Regression test for the intermittent {@code ConcurrentModificationException} thrown during | ||
| * {@code @After} integration-test cleanup and traced to | ||
| * {@link AbstractHibernateDAO#iterate(javax.persistence.Query)}. | ||
| * | ||
| * <p>That method used to close its Hibernate {@code Stream} from a {@code finalize()} override. {@code finalize()} | ||
| * runs on the GC Finalizer thread, so closing the stream there mutated the owning {@code Session}'s per-session, | ||
| * non-thread-safe JDBC {@code ResourceRegistry} (xref) concurrently with the thread that owns the session. That | ||
| * is a genuine data race which intermittently threw {@code ConcurrentModificationException} from | ||
| * {@code ResourceRegistryStandardImpl.releaseResources} during an unrelated commit/rollback. The fix closes the | ||
| * stream on the owning thread once the iteration is exhausted. This test guards against reintroducing any | ||
| * stream-closing finalizer on the returned iterator.</p> | ||
| */ | ||
| public class AbstractHibernateDAOIteratorIT extends AbstractIntegrationTestWithDatabase { | ||
|
|
||
| private final MetadataValueService metadataValueService = | ||
| ContentServiceFactory.getInstance().getMetadataValueService(); | ||
|
|
||
| @Test | ||
| public void iterateIteratorMustNotCloseStreamFromFinalizer() throws Exception { | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| // findByValueLike() delegates to AbstractHibernateDAO.iterate(); the concrete (anonymous) iterator type | ||
| // is what we assert on. No matching rows are required - the wrapper iterator is created regardless. | ||
| Iterator<MetadataValue> iterator = | ||
| metadataValueService.findByValueLike(context, "no-such-metadata-value-" + System.nanoTime()); | ||
| assertNotNull(iterator); | ||
|
|
||
| // The returned iterator MUST NOT declare its own finalize(): closing the backing Hibernate Stream from | ||
| // the GC Finalizer thread is exactly the cross-thread access to the non-thread-safe JDBC | ||
| // ResourceRegistry that caused the flaky ConcurrentModificationException. | ||
| try { | ||
| iterator.getClass().getDeclaredMethod("finalize"); | ||
| fail("AbstractHibernateDAO.iterate() iterator must not declare a finalize() override - closing the " | ||
| + "Hibernate Stream on the GC Finalizer thread races the owning thread's non-thread-safe " | ||
| + "JDBC ResourceRegistry and intermittently throws ConcurrentModificationException."); | ||
| } catch (NoSuchMethodException expected) { | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| // good: no stream-closing finalizer on the iterator | ||
| } | ||
|
|
||
| // It must still iterate to exhaustion and close its cursor on THIS (the owning) thread without error. | ||
| while (iterator.hasNext()) { | ||
| assertNotNull(iterator.next()); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.