diff --git a/docs/decisions/2026-11-12-mcp-turns-off-at-request-time.md b/docs/decisions/2026-11-12-mcp-turns-off-at-request-time.md index 19f8b1571324..6fd94c813323 100644 --- a/docs/decisions/2026-11-12-mcp-turns-off-at-request-time.md +++ b/docs/decisions/2026-11-12-mcp-turns-off-at-request-time.md @@ -1,7 +1,7 @@ # MCP turns off at request time, when its app is disabled or its setting is off - **Status:** Accepted -- **Revisions:** v1 2026-11-12 (initial) +- **Revisions:** v1 2026-11-12 (initial); v2 2026-11-18 (app state read in the background, not per request) - **Deciders:** Vishnu Jain - **Guard:** `McpAvailabilityIT` - **Related:** #37687, #29201, #30041 @@ -29,14 +29,17 @@ kept answering, and an uninstalled app is re-seeded at the next start. Setting follows at once, other servers when the settings watcher picks the change up (`watchIntervalSeconds`, 10 by default). `SettingsCache` was not used because it does not cache a missing value, so an install that never saved the setting would query on every request. -- The app is read through the entity cache: the server that took the click follows at once, - other servers when their entry expires (30 seconds by default). +- The app's state is kept in memory and re-read through the entity cache every 2 seconds in the + background, starting when MCP is mounted. A request never reads the database for it: v1 read it + per request, so once the cached entry expired, a database outage made every `/mcp` request hang + on that read instead of reaching the auth check that answers 503 with `Retry-After`. A failed + re-read keeps the last state. The server that took the click follows within about 2 seconds, + other servers when their entity cache entry expires (30 seconds by default) plus up to 2 seconds. ## Consequences Disable stops MCP and Enable brings it back, with no restart. Uninstall stops MCP until the next -start re-seeds the app; until then each refused request runs one indexed lookup, because a -missing app is not cached for `Include.ALL`. A refusal is a bare 404 status, not `sendError`, because the server maps +start re-seeds the app. A refusal is a bare 404 status, not `sendError`, because the server maps 404 errors to the UI page. A deployment that disabled the app but kept using MCP, which worked while the app state was ignored, loses MCP on upgrade until the app is enabled. A new MCP route must sit under `/mcp/` or check `McpAvailabilityFilter.isMcpAvailable()` itself, or it keeps diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/MockResponseGate.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/MockResponseGate.java index 3af3ff8f06b7..8cea5c4b38bd 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/MockResponseGate.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/MockResponseGate.java @@ -14,6 +14,7 @@ public final class MockResponseGate { private final CountDownLatch arrived = new CountDownLatch(1); private final CountDownLatch released = new CountDownLatch(1); + private final CountDownLatch completed = new CountDownLatch(1); /** Blocks the mock's handler thread until {@link #release()}, or {@link #MAX_HOLD} passes. */ public void holdResponse() { @@ -30,6 +31,19 @@ public void release() { released.countDown(); } + /** Called by the mock once the held request has been answered. */ + public void complete() { + completed.countDown(); + } + + /** + * Waits until the held request has been answered, so a test that releases it cannot have that + * late answer land in the next test. + */ + public boolean awaitCompletion(Duration timeout) { + return awaitQuietly(completed, timeout); + } + private static boolean awaitQuietly(CountDownLatch latch, Duration timeout) { try { return latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java index a51cbad60346..fe1880eab72d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java @@ -80,11 +80,16 @@ MockResponseGate holdNextResponse() { public void handle(HttpExchange exchange) throws IOException { Map form = MockHttp.formParameters(exchange); journal.record(exchange, form); - Optional.ofNullable(pendingGates.poll()).ifPresent(MockResponseGate::holdResponse); - if (isRegisteredClient(exchange, form)) { - respondToGrant(exchange, form); - } else { - respondError(exchange, UNAUTHORIZED, INVALID_CLIENT); + Optional gate = Optional.ofNullable(pendingGates.poll()); + gate.ifPresent(MockResponseGate::holdResponse); + try { + if (isRegisteredClient(exchange, form)) { + respondToGrant(exchange, form); + } else { + respondError(exchange, UNAUTHORIZED, INVALID_CLIENT); + } + } finally { + gate.ifPresent(MockResponseGate::complete); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDeleteRaceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDeleteRaceIT.java index 17f96bf1435b..fb89510b337b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDeleteRaceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDeleteRaceIT.java @@ -76,12 +76,16 @@ class DataProductDeleteRaceIT { private static final Duration BLOCKED_WITHIN = Duration.ofSeconds(60); private static final String CASCADE_PAUSE_EXTENSION = "dataProduct.cascadePause"; + // MySQL reports the table each blocked transaction waits on; its statement text in + // innodb_trx missed the waiters on CI, where the requests then ran into the 50s lock timeout. private static final String MYSQL_LOCK_WAITS = """ - SELECT trx_query FROM information_schema.innodb_trx WHERE trx_state = 'LOCK WAIT'"""; + SELECT DISTINCT w.REQUESTING_ENGINE_TRANSACTION_ID, l.OBJECT_NAME AS waiting + FROM performance_schema.data_lock_waits w + JOIN performance_schema.data_locks l ON l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID"""; private static final String POSTGRES_LOCK_WAITS = """ - SELECT query FROM pg_stat_activity + SELECT query AS waiting FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND datname = current_database()"""; private static final String DATA_PRODUCT_ROWS = """ @@ -277,10 +281,8 @@ private static CompletableFuture async(Runnable request) { } /** - * Waits until {@code request} has returned or {@code waiters} statements on {@code tables} are - * waiting on a row lock. Statements are matched on the table, not the row id: the blocked - * statement need not name the held row (a MySQL run once waited the full minute on a statement - * without the data product's id), and Postgres shows placeholders instead of bound values. + * Waits until {@code request} has returned or {@code waiters} transactions wait on a row lock in + * {@code tables}: the locked table on MySQL, the waiting statement's text on Postgres. */ private static void awaitBlocked(CompletableFuture request, int waiters, List tables) { Awaitility.await("request done or %d statements waiting on a row lock".formatted(waiters)) @@ -293,7 +295,8 @@ private static long lockWaiters(List tables) { boolean mysql = TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL; String waiting = mysql ? MYSQL_LOCK_WAITS : POSTGRES_LOCK_WAITS; List statements = - lockProbe.withHandle(h -> h.createQuery(waiting).mapTo(String.class).list()); + lockProbe.withHandle( + h -> h.createQuery(waiting).map((row, ctx) -> row.getString("waiting")).list()); return statements.stream() .filter(sql -> sql != null && tables.stream().anyMatch(table -> mentionsTable(sql, table))) .count(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MetricResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MetricResourceIT.java index 3e333706a2e8..0cab140c5cf3 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MetricResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MetricResourceIT.java @@ -2819,6 +2819,9 @@ void put_reingestingANewExpressionChangesOnlyTheExpression(TestNamespace ns) { curated.setExperts(List.of(shared.USER2_REF)); patchEntity(curated.getId().toString(), curated); patchMetricReviewers(metric.getId(), List.of(shared.USER1_REF)); + // The reviewer change starts an approval run that writes In Review asynchronously; let it land + // first so the baseline status is the one the bot's re-ingest must leave unchanged. + awaitApprovalTask(metric); Metric beforeRerun = getEntityWithFields(metric.getId().toString(), curatedFields); assertEquals(List.of(shared.USER1_REF.getId()), ids(beforeRerun.getReviewers())); assertEquals(List.of(shared.USER2_REF.getId()), ids(beforeRerun.getExperts())); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyLibraryPreviewIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyLibraryPreviewIT.java index 3c94c15dfde0..0fa5452d8415 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyLibraryPreviewIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyLibraryPreviewIT.java @@ -156,7 +156,7 @@ void libraryPreviewCannotReadDeniedWorkingDefinitions(TestNamespace ns) { Map.entry("dcat", 48), Map.entry("dpv", 3688), Map.entry("epcis", 199), - Map.entry("fhir", 16404), + Map.entry("fhir", 15673), Map.entry("fibo", 9901), Map.entry("foaf", 100), Map.entry("gs1", 1071), diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoOidcConfidentialLoginIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoOidcConfidentialLoginIT.java index 6909afd54740..9ff69ddd4655 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoOidcConfidentialLoginIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoOidcConfidentialLoginIT.java @@ -280,6 +280,9 @@ void failingTokenEndpointEndsOnTheSignInPage(TestNamespace ns) { assertLoginEndsOnSignIn(timedOut, login(timedOut), TOKEN_EXCHANGE_FAILED); } finally { unanswered.release(); + // The released exchange still mints an ID token; let it land before the next test reads the + // provider's last issued token. + unanswered.awaitCompletion(Duration.ofSeconds(10)); } assertNoAccountFor(identity); } diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpAvailabilityFilter.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpAvailabilityFilter.java index 1810c8f9d5d0..1819febf02db 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpAvailabilityFilter.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpAvailabilityFilter.java @@ -1,5 +1,8 @@ package org.openmetadata.mcp; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -7,6 +10,9 @@ import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.openmetadata.schema.api.configuration.MCPConfiguration; import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.type.Include; @@ -21,6 +27,23 @@ */ public class McpAvailabilityFilter implements Filter { + private static final long APP_STATE_REFRESH_SECONDS = 2; + private static final ScheduledExecutorService APP_STATE_REFRESHER = + Executors.newSingleThreadScheduledExecutor( + Thread.ofPlatform().daemon().name("mcp-availability").factory()); + + /** + * The app's state is served from memory and re-read in the background, so a request never waits + * on the database: during an outage MCP keeps the last state it read, and its auth answers 503 + * instead of the request hanging on this read. A failed re-read keeps the previous state. + */ + private static final LoadingCache APP_ACTIVE = + CacheBuilder.newBuilder() + .maximumSize(1) + .build( + CacheLoader.asyncReloading( + CacheLoader.from(McpAvailabilityFilter::readAppActive), APP_STATE_REFRESHER)); + @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { @@ -50,14 +73,25 @@ private static boolean isEnabledInSettings() { return config == null || Boolean.TRUE.equals(config.getEnabled()); } + /** Starts re-reading the app's state in the background, beginning while the database is up. */ + public static void startAppStateRefresh() { + APP_STATE_REFRESHER.scheduleWithFixedDelay( + () -> APP_ACTIVE.refresh(McpAppConstants.MCP_APP_NAME), + 0, + APP_STATE_REFRESH_SECONDS, + TimeUnit.SECONDS); + } + + private static boolean isAppActive() { + return APP_ACTIVE.getUnchecked(McpAppConstants.MCP_APP_NAME); + } + /** * Through the entity cache. Disabling the app soft-deletes it; uninstalling removes it until a * restart re-seeds it. */ - private static boolean isAppActive() { - App app = - Entity.findEntityByNameOrNull( - Entity.APPLICATION, McpAppConstants.MCP_APP_NAME, Include.ALL); + private static boolean readAppActive(String appName) { + App app = Entity.findEntityByNameOrNull(Entity.APPLICATION, appName, Include.ALL); return app != null && !Boolean.TRUE.equals(app.getDeleted()); } } diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java index a518ce42d3d5..5b54ba479409 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java @@ -401,6 +401,7 @@ public void stop() { /** FORWARD covers the SSO callback, which /callback forwards to /mcp/callback. */ private static void registerAvailabilityFilter(Environment environment) { + McpAvailabilityFilter.startAppStateRefresh(); environment .servlets() .addFilter("mcp-availability", new McpAvailabilityFilter()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/ContextFileFqnRepair.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/ContextFileFqnRepair.java index 92456889befa..306390d3bb93 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/ContextFileFqnRepair.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/ContextFileFqnRepair.java @@ -34,6 +34,7 @@ import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.cache.CacheBundle; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.locator.ConnectionType; @@ -242,6 +243,9 @@ private static Outcome repair( } EntityRepository.invalidateCacheForEntity(CONTEXT_FILE, misnamed.id(), misnamed.storedFqn()); EntityRepository.invalidateCacheForEntity(CONTEXT_FILE, misnamed.id(), misnamed.derivedFqn()); + // A lookup of the derived FQN before the repair left a not-found marker that the entity + // cache helper above does not clear. + CacheBundle.invalidateEntity(CONTEXT_FILE, misnamed.id(), misnamed.derivedFqn()); reindex(repaired.get()); if (!sharing.isEmpty()) { LOG.warn( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/SamlAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/SamlAuthServletHandler.java index 49244bb0476f..d5be7046a054 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/SamlAuthServletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/SamlAuthServletHandler.java @@ -879,7 +879,12 @@ username, new CreateUser().withName(username).withEmail(email).withIsBot(false)) return UserUtil.createOrAdoptConcurrentlyCreatedUser( () -> UserUtil.addOrUpdateUser(newUser), - () -> Entity.getEntityByName(Entity.USER, username, USER_FIELDS, Include.NON_DELETED), + // From the database: the losing login's own miss can leave a not-found marker that + // would + // hide the account the winning login just committed. + () -> + Entity.getEntityByName( + Entity.USER, username, USER_FIELDS, Include.NON_DELETED, false), email); } throw new AuthenticationException("User not found and self-signup is disabled");