Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Jdbi stays on a release that does not pin virtual threads, and Collate runs the same Jdbi version

- **Status:** Accepted
- **Revisions:** v1 2026-10-13 (initial) · v2 2026-10-14 (eager handler cost of Jdbi 3.38+ and its mitigation)
- **Deciders:** Mohit Yadav
- **Guard:** `JdbiVirtualThreadPinningTest`; reviewer for Collate's `jdbi3.version`
- **Related:** #35373; `pom.xml` `jdbi3.version`; `jdbi3/locator/ConnectionAwareSql*`

## Context

Jdbi before 3.45.4 opens an on-demand handle inside a `synchronized` block
(`MemoizingSupplier.init`). On Java 21 a virtual thread that parks while holding a monitor keeps its
carrier thread. `HikariDataSource.getConnection` parks when the pool is exhausted, and with leak
detection on (60 s by default) it also queues on the lock of the scheduler that tracks leaks. Once as
many virtual threads as there are carriers were parked there, the thread next in line for that lock
had no carrier to run on, and the server's virtual-thread scheduler stopped for good.

That was the integration-test "wedge": async deletes stopped, requests that wait on virtual-thread
work (search document builds) hung until the client's 300 s timeout, and MySQL timed out on row locks
the stuck threads held. Twelve stall dumps from five CI runs, across all three database and search
pairings, showed the same four threads pinned inside `MemoizingSupplier.init` on a four-CPU runner.
Production runs the same code path.

## Decision

`jdbi3.version` is 3.45.4 or later. It is set to the version `dropwizard-jdbi3` is built against
(3.49.5 for Dropwizard 5.0.0), which also lines `jdbi3-core` and `jdbi3-sqlobject` up with the
`jdbi3-guava` that Dropwizard brings in.

The `ConnectionAwareSql*` annotations register their handlers with
`@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, …)`, which only Jdbi 3.38 and later
provide. Collate compiles against OpenMetadata and pins `jdbi3.version` itself, so a Jdbi change
lands in both repositories together and they run the same version.

## Consequences

Opening a handle no longer pins a virtual thread, so a slow or exhausted pool delays requests instead
of stopping the scheduler. A Jdbi bump is now a two-repository change. A Collate build left on an
older Jdbi cannot see the handler annotation and cannot run OpenMetadata's DAOs. Revisit the floor if
the server moves to a JDK where monitors no longer pin virtual threads (JEP 491, JDK 24).

## Amendment
v2, 2026-10-14. Jdbi 3.38 and later build every method's handler, with its own configuration copy,
each time a SQL object is attached, which made each on-demand DAO call allocate about ten times more
than on 3.37.1 and slowed the workflow-event consumer enough to time out approval ITs. The version
floor stands; OpenMetadata builds handlers lazily instead
(ADR:2026-10-14-sql-objects-build-method-handlers-on-first-call).
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Cache misses that do I/O load outside the cache's lock

- **Status:** Accepted
- **Revisions:** v1 2026-10-14 (initial)
- **Deciders:** Ram Narayan Balaji
- **Guard:** `EntityCacheVirtualThreadTest`
- **Related:** #35428; #35374 and ADR:2026-10-13-jdbi-never-pins-virtual-threads-and-collate-runs-the-same-version

## Context

The server runs on JDK 21. A virtual thread that blocks while holding a Java monitor stays pinned
to its carrier, and there is one carrier per CPU. In six merge-queue stalls of the Postgres +
OpenSearch IT lane, all four carriers were pinned and the server stopped. Apart from Jdbi (fixed
in #35374), the pins were in the entity cache's Guava load, which reads Redis and the database
inside a `synchronized` on the entry. Caffeine's `get` and `ConcurrentHashMap.compute` also run
their loader inside `synchronized`, so changing cache library does not avoid it.

## Decision

Code that can run on a virtual thread does not do blocking I/O inside a cache loader, a `compute`
function, or a `synchronized` block. An entity-cache miss (`EntityRepository.loadOutsideCacheLock`)
reads the write epoch, runs the loader, `put`s the result, then re-checks the epoch and evicts
(throwing `LoaderRaceException`) if it moved.

## Consequences

Concurrent misses for one key may each run the loader once; Redis L2 absorbs most of the duplicate
reads. Switching `find` / `findByName` back to `CACHE_WITH_*.get`, or to a Caffeine loading `get`,
brings the pinning back. Revisit once the server runs on JDK 24 or later (JEP 491), where monitors
no longer pin virtual threads.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# SQL objects build a method's Jdbi handler on first call, not on every attach

- **Status:** Accepted
- **Revisions:** v1 2026-10-14 (initial)
- **Deciders:** Ram Narayan Balaji
- **Guard:** `LazySqlObjectFactoryTest`, `JdbiVirtualThreadPinningTest`
- **Related:** ADR:2026-10-13-jdbi-never-pins-virtual-threads-and-collate-runs-the-same-version; #35374; jdbi/jdbi#2601

## Context
From Jdbi 3.38, attaching a SQL object builds a handler, each with a full copy of the
configuration, for every method of the type (`ExtensionFactoryDelegate.attach`). An on-demand DAO is
attached on every call, and `getCollectionDAO().xDAO().m()` attaches `CollectionDAO` (about 150
methods) and the entity DAO (about 80). Moving from 3.37.1 to 3.49.5 for the pinning fix made every
DAO call allocate roughly ten times more. With the same IT classes on the same machine, the server
allocated 19.9 GB on 3.37.1 and 53.8 GB on 3.49.5, 66% of it inside that attach; SQL count and time
in the database were unchanged. The single workflow-event consumer, which makes 39 to 110 uncached
DAO calls per approval workflow, fell behind and approval ITs timed out on every engine. Every
pin-free Jdbi release builds handlers this way, so a version change does not avoid it.

## Decision
`JdbiUtils` registers `LazySqlObjectFactory` in front of Jdbi's `SqlObjectFactory`. It reuses the
same `ExtensionMetadata`, makes one instance configuration per attach, and builds a method's handler
the first time that method is called. `@CreateSqlObject` getters on a handle attach the nested DAO the
same lazy way. Handlers are built outside any lock, so attaching never pins a virtual thread.

## Consequences
DAO calls cost what they did on 3.37.1 while keeping the pin-free release. The factory relies on
`@Alpha` Jdbi APIs (`Extensions.findMetadata`, `ExtensionMetadata.createExtensionHandlerInvoker`) and
on `OnDemandHandleSupplier`, so a Jdbi upgrade must run `LazySqlObjectFactoryTest`. A misconfigured
DAO method now fails when it is first called rather than when its DAO is attached. Remove the
factory if Jdbi builds handlers lazily again (jdbi/jdbi#2601).
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@
import java.util.function.Function;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.function.ToLongFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
Expand Down Expand Up @@ -394,6 +395,31 @@
return readEpochByName(cacheNameKey(entityType, fqn));
}

/**
* Loads a cache miss without {@code cache.get(key)}: Guava runs the loader's Redis and database
* reads inside a per-entry {@code synchronized}, which on JDK 21 pins a virtual thread to its
* carrier. Writers bump the epoch before evicting, so re-checking it after the put drops a copy
* that raced a write. Failures come back wrapped, as {@code LoadingCache.get} throws them. See
* ADR:2026-10-14-cache-misses-that-do-io-load-outside-the-cache-lock.
*/
@VisibleForTesting
static <K> String loadOutsideCacheLock(
Cache<K, String> cache, K key, CacheLoader<K, String> loader, ToLongFunction<K> epoch)
throws ExecutionException {
try {
long startEpoch = epoch.applyAsLong(key);
String json = loader.load(key);
cache.put(key, json);
if (epoch.applyAsLong(key) != startEpoch) {
cache.invalidate(key);
throw new LoaderRaceException("Concurrent write while caching %s".formatted(key));
}
return json;
} catch (Exception e) {
throw new ExecutionException(e);
}
}

private static void bumpWriteEpoch(String entityType, UUID id, String fqn) {
if (id != null) {
try {
Expand Down Expand Up @@ -546,7 +572,7 @@
@Getter protected final Set<String> allowedFields;
public final boolean supportsSoftDelete;
@Getter protected final boolean supportsTags;
@Getter protected final boolean supportsOwners;

Check warning on line 575 in openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

View workflow job for this annotation

GitHub Actions / Build Integration Test Runtime

Not generating isSupportsOwners(): A method with that name already exists

Check warning on line 575 in openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

View workflow job for this annotation

GitHub Actions / Build Integration Test Runtime

Not generating isSupportsOwners(): A method with that name already exists

Check warning on line 575 in openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

View workflow job for this annotation

GitHub Actions / Build Integration Test Runtime

Not generating isSupportsOwners(): A method with that name already exists

Check warning on line 575 in openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

View workflow job for this annotation

GitHub Actions / maven-sonarcloud-ci

Not generating isSupportsOwners(): A method with that name already exists

Check warning on line 575 in openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

View workflow job for this annotation

GitHub Actions / openmetadata-service-unit-tests

Not generating isSupportsOwners(): A method with that name already exists

Check warning on line 575 in openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

View workflow job for this annotation

GitHub Actions / py-run-build-tests

Not generating isSupportsOwners(): A method with that name already exists
@Getter protected final boolean supportsStyle;
@Getter protected final boolean supportsLifeCycle;
@Getter protected final boolean supportsCertification;
Expand Down Expand Up @@ -1662,7 +1688,12 @@
throw new EntityNotFoundException(entityNotFound(entityType, id));
}
try (var ignored = phase("cacheGet")) {
cachedJson = CACHE_WITH_ID.get(cacheKey);
cachedJson =
loadOutsideCacheLock(
CACHE_WITH_ID,
cacheKey,
new EntityLoaderWithId(),
EntityRepository::readEpochById);
}
} else if (include == NON_DELETED
&& notFoundCache != null
Expand Down Expand Up @@ -2301,7 +2332,12 @@
throw new EntityNotFoundException(entityNotFound(entityType, fqn));
}
try (var ignored = phase("cacheGet")) {
cachedJson = CACHE_WITH_NAME.get(cacheKey);
cachedJson =
loadOutsideCacheLock(
CACHE_WITH_NAME,
cacheKey,
new EntityLoaderWithName(),
EntityRepository::readEpochByName);
}
} else if (include == NON_DELETED
&& notFoundCache != null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,16 +536,37 @@ private String addDomainFilter(String query, String domain, String index) {
return query;
}

public TestSummary getTestSummary(List<ResultSummary> testCaseResults) {
Map<String, String> entityLinkMap = new HashMap<>();
for (ResultSummary result : testCaseResults) {
TestCase testCase = Entity.getEntityByName(TEST_CASE, result.getTestCaseName(), "", ALL);
MessageParser.EntityLink entityLink =
MessageParser.EntityLink.parse(testCase.getEntityLink());
String linkString = entityLink.getFieldName() == null ? "table" : entityLink.getLinkString();
entityLinkMap.put(result.getTestCaseName(), linkString);
}
return getTestSummary(testCaseResults, entityLinkMap);
public static TestSummary getTestSummary(List<ResultSummary> testCaseResults) {
Map<String, String> summaryLinkByTestCase = getSummaryLinksOfExistingTestCases(testCaseResults);
List<ResultSummary> resultsOfExistingTestCases =
testCaseResults.stream()
.filter(result -> summaryLinkByTestCase.containsKey(result.getTestCaseName()))
.toList();
return getTestSummary(resultsOfExistingTestCases, summaryLinkByTestCase);
}

/**
* Reads the listed test cases in one batch. A test case deleted after its results were listed is
* missing from the batch, so its results drop out of the summary instead of failing the whole
* read with a 404.
*/
private static Map<String, String> getSummaryLinksOfExistingTestCases(
List<ResultSummary> testCaseResults) {
List<String> testCaseFqns =
testCaseResults.stream().map(ResultSummary::getTestCaseName).distinct().toList();
TestCaseRepository testCaseRepository =
(TestCaseRepository) Entity.getEntityRepository(TEST_CASE);
return testCaseRepository.findByNames(testCaseFqns, ALL).stream()
.collect(
Collectors.toMap(
TestCase::getFullyQualifiedName,
TestSuiteRepository::getSummaryLink,
(first, duplicate) -> first));
}

private static String getSummaryLink(TestCase testCase) {
MessageParser.EntityLink entityLink = MessageParser.EntityLink.parse(testCase.getEntityLink());
return entityLink.getFieldName() == null ? "table" : entityLink.getLinkString();
}

private static TestSummary createTestSummary(Map<String, Integer> summaryMap) {
Expand All @@ -557,7 +578,7 @@ private static TestSummary createTestSummary(Map<String, Integer> summaryMap) {
return summary;
}

private ColumnTestSummaryDefinition createColumnSummary(Map<String, Integer> summaryMap) {
private static ColumnTestSummaryDefinition createColumnSummary(Map<String, Integer> summaryMap) {
ColumnTestSummaryDefinition summary = new ColumnTestSummaryDefinition();
summary.setSuccess(summaryMap.getOrDefault("Success", 0));
summary.setFailed(summaryMap.getOrDefault("Failed", 0));
Expand Down Expand Up @@ -714,7 +735,7 @@ private Map<UUID, Integer> batchGetTestCaseCounts(List<UUID> testSuiteIds) {
CollectionDAO.EntityRelationshipCount::getCount));
}

private TestSummary getTestSummary(
private static TestSummary getTestSummary(
List<ResultSummary> testCaseResults, Map<String, String> entityLinkMap) {
record ProcessedTestCaseResults(String entityLink, String status) {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.jdbi.v3.sqlobject.SqlOperation;
import org.jdbi.v3.core.extension.annotation.UseExtensionHandler;
import org.jdbi.v3.sqlobject.SqlObjectFactory;
import org.jdbi.v3.sqlobject.statement.internal.SqlBatchHandler;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Repeatable(ConnectionAwareSqlBatchContainer.class)
@SqlOperation(SqlBatchHandler.class)
@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, value = SqlBatchHandler.class)
public @interface ConnectionAwareSqlBatch {
String value() default "";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.jdbi.v3.sqlobject.SqlOperation;
import org.jdbi.v3.core.extension.annotation.UseExtensionHandler;
import org.jdbi.v3.sqlobject.SqlObjectFactory;
import org.jdbi.v3.sqlobject.statement.internal.SqlBatchHandler;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@SqlOperation(SqlBatchHandler.class)
@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, value = SqlBatchHandler.class)
public @interface ConnectionAwareSqlBatchContainer {
ConnectionAwareSqlBatch[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.jdbi.v3.sqlobject.SqlOperation;
import org.jdbi.v3.core.extension.annotation.UseExtensionHandler;
import org.jdbi.v3.sqlobject.SqlObjectFactory;
import org.jdbi.v3.sqlobject.statement.internal.SqlQueryHandler;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Repeatable(ConnectionAwareSqlQueryContainer.class)
@SqlOperation(SqlQueryHandler.class)
@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, value = SqlQueryHandler.class)
public @interface ConnectionAwareSqlQuery {
String value() default "";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.jdbi.v3.sqlobject.SqlOperation;
import org.jdbi.v3.core.extension.annotation.UseExtensionHandler;
import org.jdbi.v3.sqlobject.SqlObjectFactory;
import org.jdbi.v3.sqlobject.statement.internal.SqlQueryHandler;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@SqlOperation(SqlQueryHandler.class)
@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, value = SqlQueryHandler.class)
public @interface ConnectionAwareSqlQueryContainer {
ConnectionAwareSqlQuery[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.jdbi.v3.sqlobject.SqlOperation;
import org.jdbi.v3.core.extension.annotation.UseExtensionHandler;
import org.jdbi.v3.sqlobject.SqlObjectFactory;
import org.jdbi.v3.sqlobject.statement.internal.SqlUpdateHandler;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Repeatable(ConnectionAwareSqlUpdateContainer.class)
@SqlOperation(SqlUpdateHandler.class)
@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, value = SqlUpdateHandler.class)
public @interface ConnectionAwareSqlUpdate {
String value() default "";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.jdbi.v3.sqlobject.SqlOperation;
import org.jdbi.v3.core.extension.annotation.UseExtensionHandler;
import org.jdbi.v3.sqlobject.SqlObjectFactory;
import org.jdbi.v3.sqlobject.statement.internal.SqlUpdateHandler;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@SqlOperation(SqlUpdateHandler.class)
@UseExtensionHandler(id = SqlObjectFactory.EXTENSION_ID, value = SqlUpdateHandler.class)
public @interface ConnectionAwareSqlUpdateContainer {
ConnectionAwareSqlUpdate[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public static Jdbi createAndSetupJDBI(Environment environment, DataSourceFactory

Jdbi jdbiInstance = new JdbiFactory().build(environment, dbFactory, "database");
jdbiInstance.setSqlLogger(new OMSqlLogger());
LazySqlObjectFactory.install(jdbiInstance);
// Set the Database type for choosing correct queries from annotations
jdbiInstance
.getConfig(SqlObjects.class)
Expand All @@ -47,6 +48,7 @@ public static Jdbi createAndSetupJDBI(DataSourceFactory dbFactory) {

Jdbi jdbiInstance = Jdbi.create(dbFactory.build(new NoopMetricRegistry(), "open-metadata-ops"));
jdbiInstance.installPlugin(new SqlObjectPlugin());
LazySqlObjectFactory.install(jdbiInstance);
jdbiInstance
.getConfig(SqlObjects.class)
.setSqlLocator(new ConnectionAwareAnnotationSqlLocator(dbFactory.getDriverClass()));
Expand Down
Loading
Loading