diff --git a/api/src/org/labkey/api/cache/CacheManager.java b/api/src/org/labkey/api/cache/CacheManager.java index 59a631f26fa..fcc81627ee2 100644 --- a/api/src/org/labkey/api/cache/CacheManager.java +++ b/api/src/org/labkey/api/cache/CacheManager.java @@ -25,6 +25,8 @@ import org.labkey.api.collections.CollectionUtils; import org.labkey.api.data.Container; import org.labkey.api.data.Project; +import org.labkey.api.exp.property.Domain; +import org.labkey.api.exp.property.DomainProperty; import org.labkey.api.mbean.LabKeyManagement; import org.labkey.api.security.User; import org.labkey.api.util.GUID; @@ -35,6 +37,8 @@ import java.lang.reflect.Field; import java.lang.reflect.InaccessibleObjectException; import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -45,7 +49,9 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BiConsumer; import java.util.function.Function; +import java.util.function.Supplier; public class CacheManager { @@ -194,13 +200,44 @@ public static void validate(String debugName, K key, @Nullable V value) LOG.error("{} attempted to cache {}, which could be mutated by callers, at key {}", debugName, valueDescription, key); } - // Flag values that hold a Container or User object - analyzeValue(value, debugName, null, 1); + // Flag values that hold a Container, User, or domain object + analyzeValue(value, debugName, null, 1, CLASSES, LOG::error); } private static final int MAX_DEPTH = 4; - private static void analyzeValue(@Nullable Object value, String cacheName, @Nullable String fieldPath, int depth) + // Domains go stale when saved, and domain saves don't clear other caches + private static final List> DOMAIN_TYPES = List.of(Domain.class, DomainProperty.class); + private static final List> UNSAFE_TYPES = List.of(Container.class, User.class, Project.class, Domain.class, DomainProperty.class); + + /** Returns the unsafe type a field declares, or the domain type it declares as a type argument (e.g., List<DomainProperty>), or null */ + private static @Nullable Class getUnsafeType(Field field) + { + boolean exempt = field.isAnnotationPresent(InvalidatedOnDomainSave.class); + Class type = field.getType(); + if (UNSAFE_TYPES.stream().anyMatch(u -> u.isAssignableFrom(type)) && !(exempt && isDomainType(type))) + return type; + + // Type arguments are checked for domain types only: Supplier and the user cache's maps are safe + if (!exempt && field.getGenericType() instanceof ParameterizedType pt) + { + for (Type arg : pt.getActualTypeArguments()) + { + Type raw = arg instanceof ParameterizedType p ? p.getRawType() : arg; + if (raw instanceof Class c && isDomainType(c)) + return c; + } + } + + return null; + } + + private static boolean isDomainType(Class type) + { + return DOMAIN_TYPES.stream().anyMatch(u -> u.isAssignableFrom(type)); + } + + private static void analyzeValue(@Nullable Object value, String cacheName, @Nullable String fieldPath, int depth, Set> analyzed, BiConsumer error) { if (value != null && depth < MAX_DEPTH) { @@ -211,42 +248,46 @@ private static void analyzeValue(@Nullable Object value, String cacheName, @Null m.entrySet().stream() .findFirst() .ifPresent(entry -> { - analyzeValue(entry.getKey(), cacheName, safeAppend(fieldPath, "Map", "_key"), depth + 1); - analyzeValue(entry.getValue(), cacheName, safeAppend(fieldPath, "Map", "_value"), depth + 1); + analyzeValue(entry.getKey(), cacheName, safeAppend(fieldPath, "Map", "_key"), depth + 1, analyzed, error); + analyzeValue(entry.getValue(), cacheName, safeAppend(fieldPath, "Map", "_value"), depth + 1, analyzed, error); }); } else if (value instanceof Collection coll) { coll.stream() .findFirst() - .ifPresent(element -> analyzeValue(element, cacheName, safeAppend(fieldPath, coll.getClass().getSimpleName(), "get(0)"), depth + 1)); + .ifPresent(element -> analyzeValue(element, cacheName, safeAppend(fieldPath, coll.getClass().getSimpleName(), "get(0)"), depth + 1, analyzed, error)); } else if (clazz.isArray() && Array.getLength(value) > 0) { - analyzeValue(Array.get(value, 0), cacheName, safeAppend(fieldPath, "Array", "[0]"), depth + 1); + analyzeValue(Array.get(value, 0), cacheName, safeAppend(fieldPath, "Array", "[0]"), depth + 1, analyzed, error); } else if (value instanceof Reference ref) { - analyzeValue(ref, cacheName, fieldPath, depth + 1); + analyzeValue(ref, cacheName, fieldPath, depth + 1, analyzed, error); + } + else if (isDomainType(clazz)) + { + error.accept("Cached value is an unsafe object - {}: {} ({})", new Object[]{cacheName, fieldPath, clazz.getName()}); } - else if (CLASSES.add(clazz)) + else if (analyzed.add(clazz)) { for (Field field : getAllInstanceFields(clazz)) { String newFieldPath = safeAppend(fieldPath, clazz.getSimpleName(), field.getName()); - Class type = field.getType(); + Class unsafeType = getUnsafeType(field); - if (Container.class.isAssignableFrom(type) || User.class.isAssignableFrom(type) || Project.class.isAssignableFrom(type)) + if (unsafeType != null) { - LOG.error("Cached value holds an unsafe object - {}: {} field {} ({})", cacheName, clazz.getName(), newFieldPath, field.getType().getName()); + error.accept("Cached value holds an unsafe object - {}: {} field {} ({})", new Object[]{cacheName, clazz.getName(), newFieldPath, unsafeType.getName()}); } - else + else if (!field.isAnnotationPresent(InvalidatedOnDomainSave.class)) { try { field.setAccessible(true); Object val = field.get(value); - analyzeValue(val, cacheName, newFieldPath, depth + 1); + analyzeValue(val, cacheName, newFieldPath, depth + 1, analyzed, error); } catch (InaccessibleObjectException e) { @@ -291,6 +332,29 @@ public interface Sealable public static class TestCase extends Assert { + private record HoldsDomain(Domain domain) {} + private record HoldsProperties(List properties) {} + private record HoldsInvalidatedDomain(@InvalidatedOnDomainSave("test") Domain domain) {} + private record HoldsContainerSupplier(Supplier container) {} + private record HoldsUsers(List users) {} + + @Test + public void testDomainHoldersFlagged() + { + record Case(Object value, boolean flagged) {} + for (Case c : List.of( + new Case(new HoldsDomain(null), true), + new Case(new HoldsProperties(List.of()), true), + new Case(new HoldsInvalidatedDomain(null), false), + new Case(new HoldsContainerSupplier(null), false), + new Case(new HoldsUsers(List.of()), false))) + { + List errors = new ArrayList<>(); + analyzeValue(c.value(), "test", null, 1, new HashSet<>(), (_, args) -> errors.add(args)); + assertEquals(c.value().getClass().getSimpleName(), c.flagged(), !errors.isEmpty()); + } + } + @Test public void testContainerKeyRejected() { diff --git a/api/src/org/labkey/api/cache/InvalidatedOnDomainSave.java b/api/src/org/labkey/api/cache/InvalidatedOnDomainSave.java new file mode 100644 index 00000000000..9e9ba32f290 --- /dev/null +++ b/api/src/org/labkey/api/cache/InvalidatedOnDomainSave.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.api.cache; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Exempts a Domain or DomainProperty field from CacheManager's cached-value check. Domain saves don't clear other + * caches, so use this only when the owning cache is evicted on save, typically from DomainKind.invalidate(). + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface InvalidatedOnDomainSave +{ + /** The code that evicts the cached holder when its domain is saved */ + String value(); +} diff --git a/api/src/org/labkey/api/data/CacheReplayCommitTask.java b/api/src/org/labkey/api/data/CacheReplayCommitTask.java index 797d273d09e..178ddd9001e 100644 --- a/api/src/org/labkey/api/data/CacheReplayCommitTask.java +++ b/api/src/org/labkey/api/data/CacheReplayCommitTask.java @@ -42,11 +42,18 @@ private record Op(@NotNull Object cache, @NotNull Kind kind, @Nullable Object ke // Insertion order is replay order; a duplicate keeps the first one's position private final Map _operations = new LinkedHashMap<>(); private final Map _reloadCounts = new HashMap<>(); + private final @Nullable DbScope _scope; + + private CacheReplayCommitTask(@Nullable DbScope scope) + { + _scope = scope; + } /** The replay task already queued in the transaction, or a newly queued one */ static CacheReplayCommitTask get(Transaction transaction) { - return transaction.addCommitTask(new CacheReplayCommitTask(), DbScope.CommitTaskOption.POSTCOMMIT); + DbScope scope = transaction instanceof DbScope.TransactionImpl impl ? impl.getScope() : null; + return transaction.addCommitTask(new CacheReplayCommitTask(scope), DbScope.CommitTaskOption.POSTCOMMIT); } /** Queues the reload unless the cache already has limit reloads queued */ @@ -112,7 +119,14 @@ public void run() { // Copy guards against concurrent modification only: when commitAndKeepConnection() runs on a transaction that // isn't the innermost, a reload registers operations here that never run, since clearCommitTasks() discards them - List.copyOf(_operations.values()).forEach(Runnable::run); + List operations = List.copyOf(_operations.values()); + + // Reload loaders query the transaction's scope, so they share one held borrow; removals and clears touch only memory + Runnable replay = () -> operations.forEach(Runnable::run); + if (null != _scope && _operations.keySet().stream().anyMatch(op -> op.kind() == Kind.RELOAD)) + _scope.runHoldingThreadConnection(replay); + else + replay.run(); } @Override @@ -152,7 +166,7 @@ private List run(CacheReplayCommitTask task) @Test public void runsOperationsInFirstRegistrationOrder() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.remove("c1", "a", op("remove a")); task.reload("c1", "b", 10, op("reload b")); task.clear("c2", op("clear c2")); @@ -163,7 +177,7 @@ public void runsOperationsInFirstRegistrationOrder() @Test public void capsReloadsPerCache() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a", 2, op("1a")); task.reload("c1", "a", 2, op("1a again")); // Duplicate doesn't count against the limit task.reload("c1", "b", 2, op("1b")); @@ -175,7 +189,7 @@ public void capsReloadsPerCache() @Test public void removalDropsEarlierReloadOfTheKey() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a", 10, op("reload a")); task.reload("c1", "b", 10, op("reload b")); task.reload("c2", "a", 10, op("reload c2 a")); @@ -187,7 +201,7 @@ public void removalDropsEarlierReloadOfTheKey() @Test public void repeatedRemovalDropsReloadBetweenAndKeepsFirstPosition() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.remove("c1", "a", op("remove a")); task.reload("c1", "b", 10, op("reload b")); task.reload("c1", "a", 10, op("reload a")); @@ -198,7 +212,7 @@ public void repeatedRemovalDropsReloadBetweenAndKeepsFirstPosition() @Test public void operationRegisteredDuringReplayDoesNotRun() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a", 10, () -> { _log.add("reload a"); task.reload("c1", "b", 10, op("reload b")); @@ -211,7 +225,7 @@ public void operationRegisteredDuringReplayDoesNotRun() @Test public void droppedReloadFreesItsSlot() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a", 1, op("reload a")); task.remove("c1", "a", op("remove a")); task.reload("c1", "b", 1, op("reload b")); @@ -221,7 +235,7 @@ public void droppedReloadFreesItsSlot() @Test public void filterDropsEarlierMatchingReloads() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a1", 2, op("reload a1")); task.reload("c1", "b1", 2, op("reload b1")); task.reload("c2", "a1", 2, op("reload c2 a1")); @@ -233,7 +247,7 @@ public void filterDropsEarlierMatchingReloads() @Test public void clearReplacesTheCachesOperationsAtItsEarliestInvalidation() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a", 1, op("reload a")); task.remove("c1", "b", op("remove b")); task.removeUsingFilter("c1", (String key) -> false, op("filter")); @@ -248,7 +262,7 @@ public void clearReplacesTheCachesOperationsAtItsEarliestInvalidation() @Test public void clearNeverRunsAfterAReloadQueuedBehindAnEarlierInvalidation() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.clear("c1", op("clear c1")); task.reload("c2", "x", 10, op("reload c2 x")); task.clear("c1", op("clear c1 again")); @@ -261,7 +275,7 @@ public void clearNeverRunsAfterAReloadQueuedBehindAnEarlierInvalidation() @Test public void clearIsAppendedWhenTheCacheHasNoEarlierInvalidation() { - CacheReplayCommitTask task = new CacheReplayCommitTask(); + CacheReplayCommitTask task = new CacheReplayCommitTask(null); task.reload("c1", "a", 1, op("reload a")); task.remove("c2", "b", op("remove c2 b")); task.clear("c1", op("clear")); @@ -271,8 +285,8 @@ public void clearIsAppendedWhenTheCacheHasNoEarlierInvalidation() @Test public void allInstancesAreEqual() { - assertEquals(new CacheReplayCommitTask(), new CacheReplayCommitTask()); - assertEquals(new CacheReplayCommitTask().hashCode(), new CacheReplayCommitTask().hashCode()); + assertEquals(new CacheReplayCommitTask(null), new CacheReplayCommitTask(null)); + assertEquals(new CacheReplayCommitTask(null).hashCode(), new CacheReplayCommitTask(null).hashCode()); } } } diff --git a/api/src/org/labkey/api/data/DbScope.java b/api/src/org/labkey/api/data/DbScope.java index d442c475309..83187ff9e87 100644 --- a/api/src/org/labkey/api/data/DbScope.java +++ b/api/src/org/labkey/api/data/DbScope.java @@ -1292,6 +1292,58 @@ public boolean isThreadConnectionActive() return getConnectionHolder().getRefCount() > 0; } + /** + * Runs the task with this thread's connection pinned, so its statements share one borrow instead of taking one apiece. + * The task must not begin a transaction or stream a large result: either would hold a second connection or defeat + * the outermost borrower's JDBC caching setup. + */ + public void runHoldingThreadConnection(Runnable task) + { + Connection held = holdThreadConnection(); + try + { + task.run(); + } + finally + { + releaseHeldConnection(held); + } + } + + /** Null when nothing was pinned */ + private @Nullable Connection holdThreadConnection() + { + // A banned thread's next borrow throws, which would skip the caller's work entirely + if (isTransactionActive() || BANNED_THREADS.contains(getEffectiveThread())) + return null; + + try + { + return getConnection(); + } + catch (SQLException | RuntimeException e) + { + LOG.debug("Proceeding without a held thread connection", e); + return null; + } + } + + /** Logs rather than throws, since callers often run after their transaction has committed */ + private void releaseHeldConnection(@Nullable Connection conn) + { + if (null == conn) + return; + + try + { + conn.close(); + } + catch (SQLException | RuntimeException e) + { + LOG.warn("Failed to release a held thread connection", e); + } + } + /** * Get a fresh connection directly from the pool... not part of the current transaction, not shared with the thread, etc. */ @@ -2977,6 +3029,11 @@ public void commitAndKeepConnection() } } + DbScope getScope() + { + return DbScope.this; + } + public void setLockTimeout(int timeout, TimeUnit units) { _lockTimeout = timeout; @@ -3451,6 +3508,51 @@ public void testLatePostCommitOrder() assertFalse(scope.isTransactionActive()); } + // Replayed cache reloads share one borrow; other post-commit tasks run without a held connection, so they can open transactions safely + @Test + public void testCacheReplaySharesThreadConnection() + { + DbScope scope = getLabKeyScope(); + assertFalse("Test thread should not already hold a connection", scope.isThreadConnectionActive()); + + for (boolean keepConnection : List.of(false, true)) + { + List seen = new ArrayList<>(); + List plainTaskHeld = new ArrayList<>(); + Runnable reload = () -> { + try (Connection conn = scope.getConnection()) + { + new SqlSelector(scope, "SELECT 1").getObject(Integer.class); + seen.add(conn); + } + catch (SQLException e) + { + throw new RuntimeSQLException(e); + } + }; + + try (Transaction t = scope.ensureTransaction()) + { + CacheReplayCommitTask replay = CacheReplayCommitTask.get(t); + replay.reload("cache", "a", 10, reload); + replay.reload("cache", "b", 10, reload); + t.addCommitTask(() -> plainTaskHeld.add(scope.isThreadConnectionActive()), CommitTaskOption.POSTCOMMIT); + if (keepConnection) + { + t.commitAndKeepConnection(); + assertTrue(scope.isTransactionActive()); + } + t.commit(); + } + + String message = "keepConnection=" + keepConnection; + assertEquals(message, 2, seen.size()); + assertSame(message + ": replayed reloads should share one borrow", seen.get(0), seen.get(1)); + assertEquals(message, List.of(false), plainTaskHeld); + assertFalse(message + ": the held connection should be released", scope.isThreadConnectionActive()); + } + } + @Test public void testCommitAndKeepConnection() { diff --git a/api/src/org/labkey/api/exp/OntologyManager.java b/api/src/org/labkey/api/exp/OntologyManager.java index aa093d78c27..4012ee38f93 100644 --- a/api/src/org/labkey/api/exp/OntologyManager.java +++ b/api/src/org/labkey/api/exp/OntologyManager.java @@ -3036,6 +3036,8 @@ public static PropertyDescriptor updatePropertyDescriptor(PropertyDescriptor pd) PROP_DESCRIPTOR_CACHE.remove(getCacheKey(pd)); // It's possible that the propertyURI has changed, thus breaking our reference DOMAIN_PROPERTIES_CACHE.clear(); + // Cached property values embed descriptor metadata (name, type) from any domain + PROPERTY_MAP_CACHE.clear(); return pd; } @@ -3217,9 +3219,8 @@ public static void invalidateDomain(Domain d) uncachePropertyDescriptors(propertyURIs); DOMAIN_DESCRIPTORS_BY_CONTAINER_CACHE.remove(d.getContainer()); - // Cached property values embed property metadata (name, type) from any domain, so these can't be narrowed - PROPERTY_MAP_CACHE.clear(); - ExperimentService.get().clearCaches(); + // Property maps aren't cleared here: descriptor updates and deletes clear them, and added properties have no values. + // Experiment caches aren't cleared either: protocols memoize object properties, but those are ad hoc, not domain members. } /** For callers that update exp.PropertyDescriptor rows directly; invalidateDomain() only covers the saved domain's own properties */ diff --git a/api/src/org/labkey/api/exp/property/DomainUtil.java b/api/src/org/labkey/api/exp/property/DomainUtil.java index 404a003b594..d56c422d9a8 100644 --- a/api/src/org/labkey/api/exp/property/DomainUtil.java +++ b/api/src/org/labkey/api/exp/property/DomainUtil.java @@ -789,7 +789,7 @@ public static Domain createDomain( } // Issue 48810: if not creating from templateInfo, validate reserved field names based on domainKind - boolean strictFieldValidation = arguments != null ? (Boolean) arguments.getOrDefault("strictFieldValidation", true) : true; + boolean strictFieldValidation = arguments == null || (Boolean) arguments.getOrDefault("strictFieldValidation", true); DomainKind validateDomainKind = templateInfo == null && strictFieldValidation ? kind : null; ValidationException ve = DomainUtil.validateProperties(null, domain, validateDomainKind, null, user); diff --git a/experiment/src/org/labkey/experiment/api/property/DomainImpl.java b/experiment/src/org/labkey/experiment/api/property/DomainImpl.java index d71056ada79..a8bfac27e54 100644 --- a/experiment/src/org/labkey/experiment/api/property/DomainImpl.java +++ b/experiment/src/org/labkey/experiment/api/property/DomainImpl.java @@ -23,6 +23,7 @@ import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import org.json.JSONObject; +import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.labkey.api.audit.AbstractAuditTypeProvider; @@ -41,6 +42,7 @@ import org.labkey.api.data.DbSequence; import org.labkey.api.data.DbSequenceManager; import org.labkey.api.data.ImportAliasable; +import org.labkey.api.data.JdbcType; import org.labkey.api.data.MVDisplayColumnFactory; import org.labkey.api.data.Parameter; import org.labkey.api.data.ParameterMapStatement; @@ -50,6 +52,7 @@ import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SchemaTableInfo; import org.labkey.api.data.ServerPrimaryKeyLock; +import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.SqlExecutor; import org.labkey.api.data.SqlSelector; import org.labkey.api.data.Table; @@ -68,21 +71,31 @@ import org.labkey.api.exp.DomainDescriptor; import org.labkey.api.exp.DomainNotFoundException; import org.labkey.api.exp.ExperimentException; +import org.labkey.api.exp.Lsid; import org.labkey.api.exp.MvColumn; +import org.labkey.api.exp.ObjectProperty; import org.labkey.api.exp.OntologyManager; import org.labkey.api.exp.PropertyColumn; import org.labkey.api.exp.PropertyDescriptor; import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.TemplateInfo; +import org.labkey.api.exp.api.ExpDataClass; +import org.labkey.api.exp.api.ExpObject; +import org.labkey.api.exp.api.ExpSampleType; import org.labkey.api.exp.api.ExperimentService; +import org.labkey.api.exp.api.SampleTypeService; import org.labkey.api.exp.api.StorageProvisioner; +import org.labkey.api.exp.list.ListDefinition; +import org.labkey.api.exp.list.ListService; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainAuditProvider; import org.labkey.api.exp.property.DomainKind; import org.labkey.api.exp.property.DomainProperty; import org.labkey.api.exp.property.DomainTemplate; import org.labkey.api.exp.property.DomainUtil; +import org.labkey.api.exp.property.PropertyService; import org.labkey.api.exp.query.ExpSchema; +import org.labkey.api.gwt.client.model.GWTConditionalFormat; import org.labkey.api.gwt.client.model.GWTIndex; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; import org.labkey.api.query.BatchValidationException; @@ -106,6 +119,10 @@ import org.labkey.api.util.TestContext; import org.labkey.api.view.ActionURL; import org.labkey.api.writer.ContainerUser; +import org.labkey.experiment.api.DataClass; +import org.labkey.experiment.api.ExpDataClassImpl; +import org.labkey.experiment.api.ExpSampleTypeImpl; +import org.labkey.experiment.api.MaterialSource; import org.labkey.experiment.exp.property.DomainPropertyAuditProvider; import java.sql.SQLException; @@ -122,6 +139,7 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.locks.Lock; +import java.util.function.Supplier; import static org.labkey.api.data.ColumnRenderPropertiesImpl.STORAGE_UNIQUE_ID_SEQUENCE_PREFIX; import static org.labkey.api.exp.query.ExpSchema.DerivationDataScopeType.ChildOnly; @@ -684,12 +702,15 @@ public void save(User user, boolean allowAddBaseProperty, boolean saveOnlyIfNotE // Compile audit info for every property change List propertyAuditInfo = new ArrayList<>(); + boolean descriptorsChanged = false; + // Issue 8978: Delete first for (DomainPropertyImpl impl : _properties) { if (impl._deleted || (impl.isRecreateRequired())) { impl.delete(user); + descriptorsChanged = true; propsDropped.add(impl); propChanged = true; propertyAuditInfo.add(new PropertyChangeAuditInfo(impl, false)); @@ -800,10 +821,13 @@ else if (impl.isNew()) String oldValidators = null != pdOld ? PropertyChangeAuditInfo.renderValidators(pdOld) : null; String oldConditionalFormats = null != pdOld ? PropertyChangeAuditInfo.renderConditionalFormats(pdOld) : null; impl.save(user, _dd, sortOrder++); // Automatically preserve order + descriptorsChanged |= !isImplNew && null != pdOld; - String defaultValue = impl.getDefaultValue(); - Object converted = null != defaultValue ? impl.getPropertyType().convert(defaultValue) : null; - defaultValueMap.put(impl, converted); + if (impl.isDefaultValueSet()) + { + String defaultValue = impl.getDefaultValue(); + defaultValueMap.put(impl, null != defaultValue ? impl.getPropertyType().convert(defaultValue) : null); + } if (isImplNew) propertyAuditInfo.add(new PropertyChangeAuditInfo(impl, true)); @@ -827,13 +851,29 @@ else if (null != pdOld) domainProperty.save(user, _dd, order); } - try - { - DefaultValueService.get().setDefaultValues(getContainer(), defaultValueMap); - } - catch (ExperimentException e) + // Cached property values embed descriptor metadata (name, type) from any domain + if (descriptorsChanged) + OntologyManager.clearPropertyCache(); + + // Loaded domains carry null defaults and setDefaultValues() replaces every stored one, so overlay only those explicitly set or cleared + if (!defaultValueMap.isEmpty()) { - throw new RuntimeException(e); + try + { + Map stored = isDomainNew ? Map.of() : DefaultValueService.get().getDefaultValues(getContainer(), this); + Map defaults = new HashMap<>(stored); + defaults.putAll(defaultValueMap); + + // Bean copies set null defaults on every new property, so skip the rewrite when nothing would change + Map nonNull = new HashMap<>(defaults); + nonNull.values().removeIf(Objects::isNull); + if (!nonNull.equals(stored)) + DefaultValueService.get().setDefaultValues(getContainer(), defaults); + } + catch (ExperimentException e) + { + throw new RuntimeException(e); + } } _new = false; @@ -1055,14 +1095,14 @@ private CalculatedFieldsUpdate determineCalculatedFieldsUpdates(@Nullable List propsAdded) throws SQLException, BatchValidationException { - SchemaTableInfo table = StorageProvisioner.get().getSchemaTableInfo(this); - DbScope scope = table.getSchema().getScope(); - SqlDialect dialect = table.getSqlDialect(); - List uniqueIdProps = propsAdded.stream().filter(DomainProperty::isUniqueIdField).toList(); if (uniqueIdProps.isEmpty()) return; + SchemaTableInfo table = StorageProvisioner.get().getSchemaTableInfo(this); + DbScope scope = table.getSchema().getScope(); + SqlDialect dialect = table.getSqlDialect(); + Set uniqueIndexCols = new LinkedHashSet<>(); // Find the uniqueIndexCols so we can use these for selecting items to update the uniqueIds of, // but exclude the uniqueId fields themselves. @@ -1593,6 +1633,118 @@ public DomainTemplate getTemplate() @TestWhen(TestWhen.When.BVT) public static class TestCase extends Assert { + private final List _lists = new ArrayList<>(); + private final List _expObjects = new ArrayList<>(); + private String _objectLsid; + + @After + public void cleanup() throws DomainNotFoundException + { + if (_objectLsid != null) + OntologyManager.deleteOntologyObject(_objectLsid, JunitUtil.getTestContainer(), true); + for (ListDefinition list : _lists) + list.delete(TestContext.get().getUser()); + for (ExpObject o : _expObjects) + o.delete(TestContext.get().getUser()); + } + + private Domain createList(Container c, User user, String fieldName) throws Exception + { + ListDefinition list = ListService.get().createList(c, "DomainImplTest" + GUID.makeHash(), ListDefinition.KeyType.AutoIncrementInteger); + list.setKeyName("Key"); + Objects.requireNonNull(list.getDomain()).addProperty(new PropertyStorageSpec(fieldName, JdbcType.VARCHAR)); + list.save(user); + _lists.add(list); + return Objects.requireNonNull(list.getDomain()); + } + + // A domain loaded from the database doesn't carry its stored default values, so its save must not drop them + @Test + public void saveExistingDomainKeepsDefaultValues() throws Exception + { + Container c = JunitUtil.getTestContainer(); + User user = TestContext.get().getUser(); + String domainURI = createList(c, user, "Color").getTypeURI(); + Domain created = Objects.requireNonNull(PropertyService.get().getDomain(c, domainURI)); + DefaultValueService.get().setDefaultValues(c, Map.of(created.getPropertyByName("Color"), "Blue")); + assertEquals("Blue", DefaultValueService.get().getDefaultValues(c, created).get(created.getPropertyByName("Color"))); + + Domain loaded = Objects.requireNonNull(PropertyService.get().getDomain(c, domainURI, true)); + loaded.addProperty(new PropertyStorageSpec("Size", JdbcType.INTEGER)); + loaded.save(user); + + Domain saved = Objects.requireNonNull(PropertyService.get().getDomain(c, domainURI)); + assertEquals("Blue", DefaultValueService.get().getDefaultValues(c, saved).get(saved.getPropertyByName("Color"))); + + Domain cleared = Objects.requireNonNull(PropertyService.get().getDomain(c, domainURI, true)); + cleared.getPropertyByName("Color").setDefaultValue(null); + cleared.save(user); + assertNull(DefaultValueService.get().getDefaultValues(c, cleared).get(cleared.getPropertyByName("Color"))); + } + + // Adding a list must leave cached property values and formats warm; renaming a property must refresh the values + @Test + public void listSaveInvalidatesOnlyChangedDescriptors() throws Exception + { + Container c = JunitUtil.getTestContainer(); + User user = TestContext.get().getUser(); + String domainURI = createList(c, user, "Color").getTypeURI(); + String colorURI = Objects.requireNonNull(PropertyService.get().getDomain(c, domainURI)).getPropertyByName("Color").getPropertyURI(); + _objectLsid = new Lsid("JUnit", "DomainImpl", GUID.makeHash()).toString(); + OntologyManager.ensureObject(c, _objectLsid); + OntologyManager.insertProperties(c, user, null, new ObjectProperty(_objectLsid, c, colorURI, "Blue", PropertyType.STRING)); + + Map values = OntologyManager.getPropertyObjects(c, _objectLsid); + List formats = DomainPropertyManager.get().getConditionalFormats(c); + createList(c, user, "Size"); + assertSame(values, OntologyManager.getPropertyObjects(c, _objectLsid)); + assertSame(formats, DomainPropertyManager.get().getConditionalFormats(c)); + + Domain domain = Objects.requireNonNull(PropertyService.get().getDomain(c, domainURI, true)); + domain.getPropertyByName("Color").setName("Colour"); + domain.save(user); + assertEquals("Colour", OntologyManager.getPropertyObjects(c, _objectLsid).get(colorURI).getName()); + } + + private void addFormattedColor(Domain domain, User user) throws ChangePropertyDescriptorException + { + ConditionalFormat format = new ConditionalFormat(); + format.setFilter(new SimpleFilter(FieldKey.fromParts(GWTConditionalFormat.COLUMN_NAME), "red").toQueryString(GWTConditionalFormat.DATA_REGION_NAME)); + format.setBold(true); + domain.addProperty(new PropertyStorageSpec("Color", JdbcType.VARCHAR)).setConditionalFormats(List.of(format)); + domain.save(user); + } + + // Experiment caches hold row beans and wrappers fetch their own domain, so domain saves needn't clear those caches + @Test + public void domainSaveKeepsExperimentCachesWarm() throws Exception + { + Container c = JunitUtil.getTestContainer(); + User user = TestContext.get().getUser(); + String name = "DomainImplTest" + GUID.makeHash(); + ExpSampleType st = SampleTypeService.get().createSampleType(c, user, name, null, List.of(new GWTPropertyDescriptor("Name", "string")), List.of(), -1, -1, -1, -1, null); + _expObjects.add(st); + ExpDataClass dc = ExperimentService.get().createDataClass(c, user, name, null, List.of(), List.of(), null, null); + _expObjects.add(dc); + Supplier cachedSampleType = () -> (ExpSampleTypeImpl) SampleTypeService.get().getSampleType(c, name); + Supplier cachedDataClass = () -> (ExpDataClassImpl) ExperimentService.get().getDataClass(c, name); + MaterialSource sampleTypeBean = cachedSampleType.get().getDataObject(); + DataClass dataClassBean = cachedDataClass.get().getDataObject(); + + createList(c, user, "Size"); + addFormattedColor(st.getDomain(true), user); + addFormattedColor(dc.getDomain(true), user); + + assertSame(sampleTypeBean, cachedSampleType.get().getDataObject()); + assertSame(dataClassBean, cachedDataClass.get().getDataObject()); + for (Domain domain : List.of(cachedSampleType.get().getDomain(), cachedDataClass.get().getDomain())) + { + DomainProperty color = domain.getPropertyByName("Color"); + assertNotNull(domain.getTypeURI(), color); + assertEquals(domain.getTypeURI(), 1, color.getConditionalFormats().size()); + } + } + @Test public void saveAfterGetReadOnlyDomain() { diff --git a/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java b/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java index ebbd8eb9452..aced3b1343f 100644 --- a/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java +++ b/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java @@ -83,6 +83,7 @@ public class DomainPropertyImpl implements DomainProperty private List _validators; private List _formats; private String _defaultValue; + private boolean _defaultValueSet; public DomainPropertyImpl(DomainImpl type, PropertyDescriptor pd) { @@ -610,6 +611,7 @@ public void setDefaultValueType(String defaultValueTypeName) public void setDefaultValue(String value) { _defaultValue = value; + _defaultValueSet = true; } public String getDefaultValue() @@ -617,6 +619,12 @@ public String getDefaultValue() return _defaultValue; } + // Distinguishes an explicitly cleared default from one never loaded from DefaultValueService + public boolean isDefaultValueSet() + { + return _defaultValueSet; + } + @Override public Lookup getLookup() { @@ -805,7 +813,7 @@ public boolean isDirty() public void delete(User user) { DomainPropertyManager.get().removeValidatorsForPropertyDescriptor(getContainer(), getPropertyId()); - DomainPropertyManager.get().deleteConditionalFormats(getPropertyId()); + DomainPropertyManager.get().deleteConditionalFormats(_pd); DomainKind kind = getDomain().getDomainKind(); if (null != kind) diff --git a/experiment/src/org/labkey/experiment/api/property/DomainPropertyManager.java b/experiment/src/org/labkey/experiment/api/property/DomainPropertyManager.java index 4a3ceb86651..9fbdf39a550 100644 --- a/experiment/src/org/labkey/experiment/api/property/DomainPropertyManager.java +++ b/experiment/src/org/labkey/experiment/api/property/DomainPropertyManager.java @@ -265,12 +265,23 @@ public void deleteAllValidatorsAndFormats(Container c) } + /** Clears every container's entry, since callers can't name the descriptor's container; prefer the PropertyDescriptor overload */ public void deleteConditionalFormats(int propertyId) { - SQLFragment sql = new SQLFragment().unsafeAppend("DELETE FROM ").append(getTinfoConditionalFormat().getSQLName()).unsafeAppend(" WHERE PropertyId = ?").addAll(propertyId); - new SqlExecutor(getExpSchema()).execute(sql); - // Blow the cache - CONDITIONAL_FORMAT_CACHE.clear(); + if (deleteConditionalFormatRows(propertyId) > 0) + CONDITIONAL_FORMAT_CACHE.clear(); + } + + public void deleteConditionalFormats(@NotNull PropertyDescriptor pd) + { + if (deleteConditionalFormatRows(pd.getPropertyId()) > 0) + CONDITIONAL_FORMAT_CACHE.remove(pd.getContainer()); + } + + private int deleteConditionalFormatRows(int propertyId) + { + SQLFragment sql = new SQLFragment().unsafeAppend("DELETE FROM ").append(getTinfoConditionalFormat()).unsafeAppend(" WHERE PropertyId = ?").addAll(propertyId); + return new SqlExecutor(getExpSchema()).execute(sql); } public static void clearCaches() @@ -284,7 +295,7 @@ public void saveConditionalFormats(User user, PropertyDescriptor prop, List new assert getKeyType() != null : "Invalid Key Type for List: " + getName(); } + boolean domainSaved = _new; try (DbScope.Transaction transaction = ExperimentService.get().getSchema().getScope().ensureTransaction(_saveLock)) { if (ensureKey) @@ -439,7 +440,9 @@ public void save(User user, boolean ensureKey, @Nullable Map new _domain = null; getDomain(); - ListManager.get().indexList(_def); + // A domain save indexes the list via ListDomainKind.invalidate() after the outermost commit + if (!domainSaved) + ListManager.get().indexList(_def); } private void ensureKey() diff --git a/list/src/org/labkey/list/model/ListDomainKind.java b/list/src/org/labkey/list/model/ListDomainKind.java index 89635b04a6e..8a0961ba3aa 100644 --- a/list/src/org/labkey/list/model/ListDomainKind.java +++ b/list/src/org/labkey/list/model/ListDomainKind.java @@ -82,6 +82,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -454,7 +455,9 @@ public Domain createDomain(GWTDomain domain, ListDomainKindProperties listProper QueryService.get().saveCalculatedFieldsMetadata(ListQuerySchema.NAME, name, null, domain.getCalculatedFields(), false, user, container); - DefaultValueService.get().setDefaultValues(container, defaultValues); + // A new domain has no stored defaults, so an all-null map would only rewrite an empty defaults object + if (defaultValues.values().stream().anyMatch(Objects::nonNull)) + DefaultValueService.get().setDefaultValues(container, defaultValues); tx.commit(); } diff --git a/study/api-src/org/labkey/api/specimen/model/SpecimenTablesProvider.java b/study/api-src/org/labkey/api/specimen/model/SpecimenTablesProvider.java index e3a75495744..6bedab6b989 100644 --- a/study/api-src/org/labkey/api/specimen/model/SpecimenTablesProvider.java +++ b/study/api-src/org/labkey/api/specimen/model/SpecimenTablesProvider.java @@ -19,6 +19,7 @@ import org.jetbrains.annotations.Nullable; import org.labkey.api.action.SpringActionController; import org.labkey.api.cache.Cache; +import org.labkey.api.cache.CacheLoader; import org.labkey.api.cache.CacheManager; import org.labkey.api.data.Container; import org.labkey.api.data.PropertyStorageSpec; @@ -58,7 +59,7 @@ public class SpecimenTablesProvider public static final String LOCATION_SPECIMEN_LIST_TABLE_NAME = "LocationSpecimenList"; public static final String SPECIMEN_WRAP_TABLE_NAME = "SpecimenWrap"; - private static final Cache DOMAIN_CREATION_CACHE = CacheManager.getBlockingCache(String.class, 1000, CacheManager.HOUR, "Specimen domain creation", null); + private static final Cache DOMAIN_CREATION_CACHE = CacheManager.getBlockingCache(String.class, 1000, CacheManager.HOUR, "Specimen domain creation", null); private final Container _container; private final User _user; @@ -99,7 +100,7 @@ public final Domain getDomain(String tableName, boolean create, boolean forUpdat // Multiple threads attempting to create the domain and provisioned table may result in a constraint // violation or a deadlock. We can't retry on PostgreSQL (SQLException kills the transaction), so use a // blocking cache to designate one thread as the creator and force all others to wait. - ret = DOMAIN_CREATION_CACHE.get(domainURI, null, (key, argument) -> { + CacheLoader creator = (_, _) -> { try (var ignore = SpringActionController.ignoreSqlUpdates()) { Domain domain = PropertyService.get().createDomain(_container, domainURI, domainKind.getKindName()); @@ -119,9 +120,7 @@ public final Domain getDomain(String tableName, boolean create, boolean forUpdat domain.setPropertyForeignKeys(domainKind.getPropertyForeignKeys(_container, SpecimenTablesProvider.this)); domain.save(_user); - - // Refresh the domain. save() doesn't populate provisioned schema and table names, e.g. - return PropertyService.get().getDomain(_container, domainURI, forUpdate); + return domain.getTypeId(); } catch (ChangePropertyDescriptorException e) { @@ -131,8 +130,16 @@ public final Domain getDomain(String tableName, boolean create, boolean forUpdat { throw new RuntimeException("Cannot create domain for table. Another process may be creating it or may have deleted it. Please try your action again.", e); } - }); + }; + // Fetch fresh: save() doesn't populate provisioned schema and table names, and the cache holds only the id + ret = PropertyService.get().getDomain(DOMAIN_CREATION_CACHE.get(domainURI, null, creator), forUpdate); + if (null == ret) + { + // The cached id outlives a domain deleted within the hour, so evict it and create again + DOMAIN_CREATION_CACHE.remove(domainURI); + ret = PropertyService.get().getDomain(DOMAIN_CREATION_CACHE.get(domainURI, null, creator), forUpdate); + } assert null != ret; // We just created this domain! } return ret; diff --git a/study/src/org/labkey/study/model/DatasetDefinition.java b/study/src/org/labkey/study/model/DatasetDefinition.java index 793a8d40866..21c1bc4e3c1 100644 --- a/study/src/org/labkey/study/model/DatasetDefinition.java +++ b/study/src/org/labkey/study/model/DatasetDefinition.java @@ -32,6 +32,7 @@ import org.labkey.api.cache.Cache; import org.labkey.api.cache.CacheLoader; import org.labkey.api.cache.CacheManager; +import org.labkey.api.cache.InvalidatedOnDomainSave; import org.labkey.api.collections.ArrayListMap; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.collections.CaseInsensitiveHashSet; @@ -1946,6 +1947,7 @@ public static Set getStandardPropertiesSet() } + @InvalidatedOnDomainSave("DatasetDomainKind.invalidate") Domain _domain = null; @Override