From 4a43a7ef8dd208a3b5f36fbd15612ea6c7b57a79 Mon Sep 17 00:00:00 2001 From: XingY Date: Thu, 5 Nov 2026 09:20:22 -0800 Subject: [PATCH 1/7] Grid filter "Choose Values" performance --- .../query/suggestions/SuggestionColumn.java | 50 ++++++ .../query/controllers/QueryController.java | 13 ++ .../labkey/query/suggestions/ColumnFact.java | 8 +- .../query/suggestions/ColumnFactsCache.java | 4 +- .../query/suggestions/ColumnFactsLoader.java | 15 +- .../suggestions/FilterSuggestionService.java | 154 ++++++++++++++++-- 6 files changed, 222 insertions(+), 22 deletions(-) diff --git a/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java b/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java index cdc2aff13c1..9b69975f32c 100644 --- a/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java +++ b/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java @@ -44,6 +44,10 @@ public enum Type { BOOLEAN, DATE, FLOAT, INT, STRING } private boolean _partialMatch; private final List _nameExpressions = new ArrayList<>(); private @Nullable List _values; + private boolean _valuesFromData; + private boolean _valuesTruncated; + private boolean _valuesHaveBlank; + private @Nullable Long _distinctCount; private @Nullable List _shapes; // Number for numeric columns, LocalDate for date columns private @Nullable Object _min; @@ -176,6 +180,52 @@ public void setValues(@Nullable List values) _values = values; } + /** + * Values read from the column's data, with what the read couldn't represent. + * + * @param truncated a value was too long to keep, so values is incomplete + * @param hasBlank some row holds null or blank; blanks are never in values + */ + public void setValues(@Nullable List values, boolean truncated, boolean hasBlank) + { + _values = values; + _valuesFromData = true; + _valuesTruncated = truncated; + _valuesHaveBlank = hasBlank; + } + + /** + * The values were read from the column's data. False for a column whose values come from its definition, such as + * a boolean or Text Choice: those are the options the column allows, which some may match no row. + */ + public boolean isValuesFromData() + { + return _valuesFromData; + } + + /** Some row holds null or blank; blanks are never in {@link #getValues()}. */ + public boolean isValuesHaveBlank() + { + return _valuesHaveBlank; + } + + /** A value was too long to keep, so {@link #getValues()} is incomplete. */ + public boolean isValuesTruncated() + { + return _valuesTruncated; + } + + /** COUNT(DISTINCT), known even when the column has too many values to list. Null when not loaded. */ + public @Nullable Long getDistinctCount() + { + return _distinctCount; + } + + public void setDistinctCount(@Nullable Long distinctCount) + { + _distinctCount = distinctCount; + } + public @Nullable List getShapes() { return _shapes; diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index 3311bb012ff..def5f037a4e 100644 --- a/query/src/org/labkey/query/controllers/QueryController.java +++ b/query/src/org/labkey/query/controllers/QueryController.java @@ -4176,6 +4176,19 @@ public Object execute(FilterSuggestionsRequest request, BindException errors) } } + /** Cached per-column values and distinct counts, so the faceted filter can skip its SELECT DISTINCT. */ + @Marshal(Marshaller.Jackson) + @RequiresPermission(ReadPermission.class) + @Action(ActionType.SelectData.class) + public static class GetColumnFacetsAction extends ReadOnlyApiAction + { + @Override + public Object execute(FilterSuggestionsRequest request, BindException errors) + { + return FilterSuggestionService.getColumnFacets(getUser(), getContainer(), request); + } + } + private SimpleFilter getFilterFromQueryForm(QueryForm form) { QuerySettings settings = form.getQuerySettings(); diff --git a/query/src/org/labkey/query/suggestions/ColumnFact.java b/query/src/org/labkey/query/suggestions/ColumnFact.java index 5cd3f08ecb1..17ddaed21f7 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFact.java +++ b/query/src/org/labkey/query/suggestions/ColumnFact.java @@ -30,8 +30,12 @@ public sealed interface ColumnFact */ record Stats(@Nullable Object min, @Nullable Object max, @Nullable Long distinctCount, boolean rangeUnknown) implements ColumnFact {} - /** @param values null when the column has more than {@link ColumnFactsCache#DISTINCT_VALUE_LIMIT} distinct values */ - record Values(@Nullable List values) implements ColumnFact + /** + * @param values null when the column has more than {@link ColumnFactsCache#DISTINCT_VALUE_LIMIT} distinct values + * @param truncated a value was too long to keep, so the list is incomplete even though it didn't overflow + * @param hasBlank some row holds null or blank; blanks are left out of values but callers may still offer them + */ + record Values(@Nullable List values, boolean truncated, boolean hasBlank) implements ColumnFact { public Values { diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java index 9b4508070f5..14bd203781e 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java @@ -683,6 +683,8 @@ private FactState apply(Plan plan) } ColumnFact stats = _cache.get(plan.statsKey()); + if (stats instanceof ColumnFact.Stats st) + column.setDistinctCount(st.distinctCount()); if (plan.kind() != Kind.STRING) { // Stats that failed or haven't loaded yet leave the range unknown, so the column isn't treated as out of range @@ -703,7 +705,7 @@ private FactState applyValues(Plan plan) { ColumnFact values = _cache.get(plan.valuesKey()); if (values instanceof ColumnFact.Values v && !v.isOverflow()) - plan.column().setValues(v.values()); + plan.column().setValues(v.values(), v.truncated(), v.hasBlank()); return FactState.of(values); } diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java index 5904d7c05dd..fcb8e8673c2 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java @@ -108,23 +108,30 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag SQLFragment sql = new SQLFragment("SELECT S.").appendIdentifier(column.getAlias()).append(" AS value FROM (") .append(selectSql) - .append(") S WHERE S.").appendIdentifier(column.getAlias()).append(" IS NOT NULL"); - // One extra row for a blank value, which is dropped, and one to detect overflow - sql = table.getSqlDialect().limitRows(sql, ColumnFactsCache.DISTINCT_VALUE_LIMIT + 2); + .append(") S"); + // Two extra rows for a null and a blank value, which are dropped, and one to detect overflow + sql = table.getSqlDialect().limitRows(sql, ColumnFactsCache.DISTINCT_VALUE_LIMIT + 3); service.bindNamedParameters(sql, parameters); service.validateNamedParameters(sql); List values = new ArrayList<>(); int count = 0; + boolean truncated = false; + boolean hasBlank = false; for (String value : new SqlSelector(table.getSchema().getScope(), sql, queryLogging).setQueryTimeout(QUERY_TIMEOUT_SECONDS).getArrayList(String.class)) { if (value == null || value.isBlank()) + { + hasBlank = true; continue; + } count++; if (value.length() <= MAX_VALUE_LENGTH) values.add(type == SuggestionColumn.Type.INT ? toIntegerString(value) : value); + else + truncated = true; } - return new ColumnFact.Values(count > ColumnFactsCache.DISTINCT_VALUE_LIMIT ? null : values); + return new ColumnFact.Values(count > ColumnFactsCache.DISTINCT_VALUE_LIMIT ? null : values, truncated, hasBlank); } @Override diff --git a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java index 8e91943bc25..f2f8ebf9bde 100644 --- a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java +++ b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java @@ -26,6 +26,9 @@ import org.labkey.api.data.CompareType; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; +import org.labkey.api.data.DbScope; +import org.labkey.api.data.SQLFragment; +import org.labkey.api.data.SqlSelector; import org.labkey.api.data.PHI; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.TableInfo; @@ -33,6 +36,8 @@ import org.labkey.api.query.FieldKey; import org.labkey.api.query.QueryDefinition; import org.labkey.api.query.QueryForm; +import org.labkey.api.exp.property.Domain; +import org.labkey.api.exp.property.DomainKind; import org.labkey.api.query.QueryService; import org.labkey.api.query.UserSchema; import org.labkey.api.query.suggestions.FilterSuggestionContext; @@ -60,6 +65,8 @@ public class FilterSuggestionService private static final int MAX_SUGGESTIONS_LIMIT = 100; private static final String FILTER_REGION = "query"; private static final String ALL_COLUMNS = "*"; + // Matches the row count at which a grid stops counting exactly and shows "100,000+" + private static final long LARGE_TABLE_ROWS = 100_000; /** * @param columns the grid's display column fieldKeys @@ -113,12 +120,14 @@ private record Context(TableInfo table, Container container, User user) implemen } } - public static @NotNull FilterSuggestionsResponse getSuggestions(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) - { - SuggestionTerm term = SuggestionTerm.parse(request.term()); - if (term.isBlank()) - return new FilterSuggestionsResponse(List.of(), true); + /** The resolved table and the filter bounding the rows its facts are read from. */ + private record Resolved(@NotNull UserSchema schema, @NotNull TableInfo table, @Nullable SimpleFilter filter, boolean readsData) {} + + /** The described columns carrying whatever facts loaded within the budget. */ + private record Filled(@NotNull TableInfo table, @NotNull List columns, boolean complete) {} + private static Resolved resolve(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) + { // Same checks and messages as QueryForm, so this fails like query-getQuery.api UserSchema schema = StringUtils.isBlank(request.schemaName()) ? null : QueryService.get().getUserSchema(user, container, request.schemaName()); QueryForm.ensureSchemaNotNull(schema); @@ -133,12 +142,13 @@ private record Context(TableInfo table, Container container, User user) implemen SimpleFilter filter = getFilter(request, container, user); // A filter on a column whose data may not be read would reveal it through the rows the filter selects boolean readsData = filter == null || isReadable(table, filter); + return new Resolved(schema, table, filter, readsData); + } - // No cached value or sample name is longer, so only the search can match - if (term.getRaw().length() > ColumnFactsLoader.MAX_VALUE_LENGTH) - return new FilterSuggestionsResponse(List.of(FilterSuggestion.search(term.getRaw())), true); - - FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, getView(schema, request, user), request.columns()); + private static Filled describeAndFill(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request, @NotNull Resolved resolved) + { + TableInfo table = resolved.table(); + FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, getView(resolved.schema(), request, user), request.columns()); List columns = described.columns(); boolean complete = true; @@ -163,8 +173,8 @@ private record Context(TableInfo table, Container container, User user) implemen try { - if (readsData) - complete &= ColumnFactsCache.get().fill(context, request.parameters(), filter, described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); + if (resolved.readsData()) + complete &= ColumnFactsCache.get().fill(context, request.parameters(), resolved.filter(), described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); } catch (RuntimeException e) { @@ -172,11 +182,125 @@ private record Context(TableInfo table, Container container, User user) implemen complete = false; } - List suggestions = FilterSuggestionRanker.rank(term, columns, getMaxSuggestions(request)); + return new Filled(table, columns, complete); + } + + public static @NotNull FilterSuggestionsResponse getSuggestions(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) + { + SuggestionTerm term = SuggestionTerm.parse(request.term()); + if (term.isBlank()) + return new FilterSuggestionsResponse(List.of(), true); + + Resolved resolved = resolve(user, container, request); + + // No cached value or sample name is longer, so only the search can match + if (term.getRaw().length() > ColumnFactsLoader.MAX_VALUE_LENGTH) + return new FilterSuggestionsResponse(List.of(FilterSuggestion.search(term.getRaw())), true); + + Filled filled = describeAndFill(user, container, request, resolved); + List suggestions = FilterSuggestionRanker.rank(term, filled.columns(), getMaxSuggestions(request)); + tagResponse(filled.table(), suggestions.size(), filled.complete()); + return new FilterSuggestionsResponse(suggestions, filled.complete()); + } + + /** + * Backs query-getColumnFacets.api: what the server already knows about each requested column, so the faceted + * filter can list values, or decide not to ask for them, without a SELECT DISTINCT over the grid. + * + * @param values the column's values, when it has few enough to list; otherwise null. Only a list with + * valuesFromData set describes the rows the request selects. + * @param valuesFromData values were read from the data the request selects. False for a column whose values come + * from its definition, such as a boolean or Text Choice, where they are the options the + * column allows and some may match no row; and for a multi-valued lookup, whose values are + * read from its target table without the request's filters or container filter. + * @param distinctCount COUNT(DISTINCT), known even when values is null. Counted in SQL, so unlike values it + * includes blank strings and does not collapse numerically equal text; expect it to exceed + * values.size() by a little rather than treating a difference as truncation. + * @param truncated a value was too long to cache, so values is incomplete and callers must query instead + * @param hasBlank some row holds null or blank, which values never includes. Only meaningful with + * valuesFromData set. + */ + public record ColumnFacet( + @NotNull String fieldKey, + @NotNull String gridFieldKey, + @NotNull String type, + @Nullable List values, + boolean valuesFromData, + @Nullable Long distinctCount, + boolean truncated, + boolean hasBlank + ) {} + + /** + * @param largeTable the table behind the query holds more rows than any grid would list values for. A coarse + * answer rather than the row estimate itself, which spans containers the caller may not read. + * @param complete every fact the request asked for was loaded. False when the budget ran out, a load failed, + * or the request's own filters meant no data could be read at all. + */ + public record ColumnFacetsResponse(@NotNull List columns, boolean largeTable, boolean complete) {} + + public static @NotNull ColumnFacetsResponse getColumnFacets(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) + { + Resolved resolved = resolve(user, container, request); + Filled filled = describeAndFill(user, container, request, resolved); + + Long estimate = resolved.readsData() ? getProvisionedRowCount(resolved.table()) : null; + boolean largeTable = estimate != null && estimate > LARGE_TABLE_ROWS; + + List facets = filled.columns().stream() + .map(c -> new ColumnFacet(c.getFieldKey(), c.getGridFieldKey(), c.getType().name(), c.getValues(), + // A multi-valued lookup's values come from its target table, unscoped by this request + c.isValuesFromData() && !c.isMultiValued(), + c.getDistinctCount(), c.isValuesTruncated(), c.isValuesHaveBlank())) + .toList(); + + // Nothing was read, so the facts say nothing about the data; don't let a caller read that as "no values" + boolean complete = filled.complete() && resolved.readsData(); + tagResponse(filled.table(), facets.size(), complete); + return new ColumnFacetsResponse(facets, largeTable, complete); + } + + private static void tagResponse(TableInfo table, int count, boolean complete) + { TracedOperation.tagActiveSpan("labkey.query", table.getPublicSchemaName() + "." + table.getPublicName()); - TracedOperation.tagActiveSpan("labkey.suggestion.count", suggestions.size()); + TracedOperation.tagActiveSpan("labkey.suggestion.count", count); TracedOperation.tagActiveSpan("labkey.suggestion.complete", complete); - return new FilterSuggestionsResponse(suggestions, complete); + } + + /** + * Postgres' own estimate for the table a provisioned domain is stored in, which costs one catalog lookup. It + * covers every container the domain spans, because that is the table a value list scans. + * + * @return null for a query with no provisioned table behind it, before that table has ever been analyzed, or on + * any other database + */ + private static @Nullable Long getProvisionedRowCount(TableInfo table) + { + Domain domain = table.getDomain(); + DomainKind kind = domain == null ? null : domain.getDomainKind(); + String schemaName = kind == null ? null : kind.getStorageSchemaName(); + String tableName = domain == null ? null : domain.getStorageTableName(); + if (schemaName == null || tableName == null) + return null; + + DbScope scope = kind.getScope(); + if (scope == null || !scope.getSqlDialect().isPostgreSQL()) + return null; + + try + { + // reltuples is a float; cast in SQL because the selector has no getter for Float + SQLFragment sql = new SQLFragment("SELECT CAST(reltuples AS BIGINT) FROM pg_class WHERE oid = to_regclass(?)") + .add(schemaName + "." + tableName); + Long estimate = new SqlSelector(scope, sql).getObject(Long.class); + // -1 means never analyzed in Postgres 14 and later; older versions report 0, indistinguishable from empty + return estimate == null || estimate < 0 ? null : estimate; + } + catch (RuntimeException e) + { + LOG.warn("Unable to estimate the row count for {}", table.getName(), e); + return null; + } } /** The first non-null token from a provider that handles the table; null keeps its facts per user. */ From 06886a7f48124da996117ec2fa1a165850645d82 Mon Sep 17 00:00:00 2001 From: XingY Date: Sun, 8 Nov 2026 22:04:10 -0800 Subject: [PATCH 2/7] CC review --- .../query/suggestions/ColumnFactsCache.java | 55 ++++++++++++------- .../query/suggestions/ColumnFactsLoader.java | 10 +++- .../suggestions/FilterSuggestionService.java | 21 +++++-- 3 files changed, 57 insertions(+), 29 deletions(-) diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java index 14bd203781e..c12235e78d4 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java @@ -251,9 +251,9 @@ public static ColumnFactsCache get() * Sets cached facts on the columns, loading missing ones and waiting for them up to the budget. * @param filter bounds the rows read from the table, but not the junction tables that multi-valued lookups read * @param tokens each table's change token, or null when its facts must not be shared across users - * @return false when some fact wasn't available within the budget + * @return what the request still doesn't know about the facts it asked for */ - public boolean fill(@NotNull FilterSuggestionContext context, @Nullable Map parameters, @Nullable SimpleFilter filter, @NotNull FilterSuggestionColumns.Described described, + public FillResult fill(@NotNull FilterSuggestionContext context, @Nullable Map parameters, @Nullable SimpleFilter filter, @NotNull FilterSuggestionColumns.Described described, @NotNull Function tokens, long budgetMs) { long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(budgetMs); @@ -282,7 +282,7 @@ public boolean fill(@NotNull FilterSuggestionContext context, @Nullable Map> loads = new ArrayList<>(); @@ -311,7 +311,20 @@ record StatsGroup(Scope scope, @Nullable String columnToken) {} } } tagRequest(plans.size(), pending, failed, !finished); - return pending == 0; + return new FillResult(pending > 0, failed > 0); + } + + /** + * @param pending a fact hadn't loaded within the budget, so asking again later may answer it + * @param failed a fact's load failed, and the failure is cached: asking again won't answer it until it expires + */ + public record FillResult(boolean pending, boolean failed) + { + /** Every fact the request asked for is in hand, whether or not any of them failed. */ + public boolean complete() + { + return !pending; + } } /** Tags the request's span with how many columns' facts were ready, since the loads run in traces of their own */ @@ -919,7 +932,7 @@ public void testFactsAndCacheHit() TableInfo table = getTable(SAMPLE_TYPE); FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "token-1", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "token-1", 30_000).complete()); Map columns = byFieldKey(described); assertEquals(Set.of("red", "green", "blue"), Set.copyOf(Objects.requireNonNull(columns.get("color").getValues()))); @@ -946,7 +959,7 @@ public void testFactsAndCacheHit() int calls = source._calls.get(); FilterSuggestionColumns.Described again = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertTrue("Cached facts should need no wait", cache.fill(context(table, _user), null, null, again, _ -> "token-1", 0)); + assertTrue("Cached facts should need no wait", cache.fill(context(table, _user), null, null, again, _ -> "token-1", 0).complete()); assertEquals(calls, source._calls.get()); assertEquals(List.of("AAAA-999999"), byFieldKey(again).get("subject").getShapes()); } @@ -969,11 +982,11 @@ public void testSharingFollowsToken() TableInfo table = getTable(SAMPLE_TYPE); User other = UserManager.getGuestUser(); - assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> null, 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> null, 30_000).complete()); assertNotNull(cache.peek(context(table, _user), null, false, "values", "color")); assertNull("Facts of a table without a token must not cross users", cache.peek(context(table, other), null, false, "values", "color")); - assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, other), "shared", true, "values", "color")); assertNull("A new token must miss", cache.peek(context(table, other), "changed", true, "values", "color")); } @@ -987,7 +1000,7 @@ public void testLookupDataIsNotShared() FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of(email)); assertTrue(byFieldKey(described).containsKey(email)); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "shared", false, "values", email)); assertNull("The table's token doesn't cover data reached through a lookup", cache.peek(context(table, UserManager.getGuestUser()), "shared", true, "values", email)); } @@ -999,7 +1012,7 @@ public void testPerUserFactsFollowToken() TableInfo table = getTable(SAMPLE_TYPE); FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("viewer")); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "before", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "before", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "before", false, "values", "viewer")); assertNull("A per-user entry must miss once the table's token changes", cache.peek(context(table, _user), "after", false, "values", "viewer")); } @@ -1012,7 +1025,7 @@ public void testCalculatedDataIsNotShared() FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("viewer")); assertTrue(byFieldKey(described).containsKey("viewer")); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "shared", false, "values", "viewer")); assertNull("A calculated value can depend on the user", cache.peek(context(table, UserManager.getGuestUser()), "shared", true, "values", "viewer")); } @@ -1026,7 +1039,7 @@ public void testLookupValuesComeFromRows() assertEquals(2, described.columns().size()); assertTrue(described.lookups().isEmpty()); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); for (SuggestionColumn column : described.columns()) assertEquals(column.getFieldKey(), List.of(_user.getDisplayName(_user)), column.getValues()); } @@ -1049,7 +1062,7 @@ public void testUndeclaredParametersAreIgnored() ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(0)); TableInfo table = getTable(SAMPLE_TYPE); - assertTrue(cache.fill(context(table, _user), Map.of("bogus", 1), null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), Map.of("bogus", 1), null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "shared", true, "values", "color")); } @@ -1071,7 +1084,7 @@ public void testAuditLoggedColumnsReadNoData() logged.add(copy); } - assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(logged, Map.of(), Set.of()), _ -> "token-2", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(logged, Map.of(), Set.of()), _ -> "token-2", 30_000).complete()); assertEquals(0, source._calls.get()); for (SuggestionColumn column : logged) { @@ -1091,7 +1104,7 @@ public void testColumnsReachedThroughAuditLoggedLookupsReadNoData() FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("CreatedBy")); SuggestionColumn createdBy = described.columns().getFirst(); - assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(described.columns(), described.lookups(), Set.of(createdBy)), _ -> "token-4", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(described.columns(), described.lookups(), Set.of(createdBy)), _ -> "token-4", 30_000).complete()); assertEquals(0, source._calls.get()); assertNull(createdBy.getValues()); } @@ -1104,7 +1117,7 @@ public void testBudget() throws Exception long start = System.currentTimeMillis(); FilterSuggestionColumns.Described cold = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertFalse(cache.fill(context(table, _user), null, null, cold, _ -> "token-3", 100)); + assertFalse(cache.fill(context(table, _user), null, null, cold, _ -> "token-3", 100).complete()); assertTrue("Budget not honored", System.currentTimeMillis() - start < 1_500); assertNull(byFieldKey(cold).get("color").getValues()); assertNull(byFieldKey(cold).get("concentration").getMin()); @@ -1113,7 +1126,7 @@ public void testBudget() throws Exception assertTrue(cache.awaitIdle(60_000)); FilterSuggestionColumns.Described warm = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertTrue("Late results should fill the cache", cache.fill(context(table, _user), null, null, warm, _ -> "token-3", 0)); + assertTrue("Late results should fill the cache", cache.fill(context(table, _user), null, null, warm, _ -> "token-3", 0).complete()); assertNotNull(byFieldKey(warm).get("color").getValues()); } @@ -1126,12 +1139,12 @@ public void testFilterBoundsFacts() SimpleFilter firstSubject = new SimpleFilter(FieldKey.fromParts("subject"), "SUBJ-000000"); FilterSuggestionColumns.Described filtered = FilterSuggestionColumns.describe(table, null, List.of("color", "thawCount")); - assertTrue(cache.fill(context(table, _user), null, firstSubject, filtered, _ -> "token-5", 30_000)); + assertTrue(cache.fill(context(table, _user), null, firstSubject, filtered, _ -> "token-5", 30_000).complete()); assertEquals(List.of("red"), byFieldKey(filtered).get("color").getValues()); assertEquals(List.of("0"), byFieldKey(filtered).get("thawCount").getValues()); FilterSuggestionColumns.Described unfiltered = FilterSuggestionColumns.describe(table, null, List.of("color")); - assertTrue(cache.fill(context(table, _user), null, null, unfiltered, _ -> "token-5", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, unfiltered, _ -> "token-5", 30_000).complete()); assertEquals("Filtered entries must not serve the unfiltered table", Set.of("red", "green", "blue"), Set.copyOf(Objects.requireNonNull(byFieldKey(unfiltered).get("color").getValues()))); } @@ -1149,13 +1162,13 @@ public void testFiltersBeyondTheTokenAreNotShared() ); for (SimpleFilter filter : unshared) { - assertTrue(filter.toString(), cache.fill(context(table, _user), null, filter, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(filter.toString(), cache.fill(context(table, _user), null, filter, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull(filter.toString(), cache.peek(context(table, _user), "shared", false, filter, "values", "color")); assertNull(filter.toString(), cache.peek(context(table, other), "shared", true, filter, "values", "color")); } SimpleFilter own = new SimpleFilter(FieldKey.fromParts("thawCount"), 0); - assertTrue(cache.fill(context(table, _user), null, own, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, own, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull("A filter on the table's own columns follows its token", cache.peek(context(table, other), "shared", true, own, "values", "color")); } diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java index fcb8e8673c2..217331ca570 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java @@ -110,16 +110,19 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag .append(selectSql) .append(") S"); // Two extra rows for a null and a blank value, which are dropped, and one to detect overflow - sql = table.getSqlDialect().limitRows(sql, ColumnFactsCache.DISTINCT_VALUE_LIMIT + 3); + int limit = ColumnFactsCache.DISTINCT_VALUE_LIMIT + 3; + sql = table.getSqlDialect().limitRows(sql, limit); service.bindNamedParameters(sql, parameters); service.validateNamedParameters(sql); List values = new ArrayList<>(); int count = 0; + int rows = 0; boolean truncated = false; boolean hasBlank = false; for (String value : new SqlSelector(table.getSchema().getScope(), sql, queryLogging).setQueryTimeout(QUERY_TIMEOUT_SECONDS).getArrayList(String.class)) { + rows++; if (value == null || value.isBlank()) { hasBlank = true; @@ -131,7 +134,10 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag else truncated = true; } - return new ColumnFact.Values(count > ColumnFactsCache.DISTINCT_VALUE_LIMIT ? null : values, truncated, hasBlank); + // Every distinct blank-ish value is its own row and is dropped without counting, so a full fetch can hide + // values even when the count is under the limit. Then the list can't be trusted to be the whole set. + boolean overflow = count > ColumnFactsCache.DISTINCT_VALUE_LIMIT || rows == limit; + return new ColumnFact.Values(overflow ? null : values, truncated, hasBlank); } @Override diff --git a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java index f2f8ebf9bde..296808414d6 100644 --- a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java +++ b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java @@ -123,8 +123,11 @@ private record Context(TableInfo table, Container container, User user) implemen /** The resolved table and the filter bounding the rows its facts are read from. */ private record Resolved(@NotNull UserSchema schema, @NotNull TableInfo table, @Nullable SimpleFilter filter, boolean readsData) {} - /** The described columns carrying whatever facts loaded within the budget. */ - private record Filled(@NotNull TableInfo table, @NotNull List columns, boolean complete) {} + /** + * The described columns carrying whatever facts loaded within the budget. + * @param failed a fact's load failed, so what's missing won't arrive by asking again + */ + private record Filled(@NotNull TableInfo table, @NotNull List columns, boolean complete, boolean failed) {} private static Resolved resolve(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) { @@ -152,6 +155,7 @@ private static Filled describeAndFill(@NotNull User user, @NotNull Container con List columns = described.columns(); boolean complete = true; + boolean failed = false; FilterSuggestionContext context = new Context(table, container, user); for (FilterSuggestionProvider provider : QueryService.get().getFilterSuggestionProviders()) { @@ -174,7 +178,11 @@ private static Filled describeAndFill(@NotNull User user, @NotNull Container con try { if (resolved.readsData()) - complete &= ColumnFactsCache.get().fill(context, request.parameters(), resolved.filter(), described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); + { + ColumnFactsCache.FillResult result = ColumnFactsCache.get().fill(context, request.parameters(), resolved.filter(), described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); + complete &= result.complete(); + failed = result.failed(); + } } catch (RuntimeException e) { @@ -182,7 +190,7 @@ private static Filled describeAndFill(@NotNull User user, @NotNull Container con complete = false; } - return new Filled(table, columns, complete); + return new Filled(table, columns, complete, failed); } public static @NotNull FilterSuggestionsResponse getSuggestions(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) @@ -254,8 +262,9 @@ public record ColumnFacetsResponse(@NotNull List columns, boolean l c.getDistinctCount(), c.isValuesTruncated(), c.isValuesHaveBlank())) .toList(); - // Nothing was read, so the facts say nothing about the data; don't let a caller read that as "no values" - boolean complete = filled.complete() && resolved.readsData(); + // Nothing was read, so the facts say nothing about the data; don't let a caller read that as "no values". + // A failed load reads the same way: its column reports no values, which is not the same as having none. + boolean complete = filled.complete() && !filled.failed() && resolved.readsData(); tagResponse(filled.table(), facets.size(), complete); return new ColumnFacetsResponse(facets, largeTable, complete); } From fd767362979ab471919c163ac6b51434d76b8c56 Mon Sep 17 00:00:00 2001 From: XingY Date: Fri, 13 Nov 2026 19:32:04 -0800 Subject: [PATCH 3/7] CC review --- .../org/labkey/query/suggestions/FilterSuggestionService.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java index 296808414d6..9cb2630b799 100644 --- a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java +++ b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java @@ -219,8 +219,7 @@ private static Filled describeAndFill(@NotNull User user, @NotNull Container con * valuesFromData set describes the rows the request selects. * @param valuesFromData values were read from the data the request selects. False for a column whose values come * from its definition, such as a boolean or Text Choice, where they are the options the - * column allows and some may match no row; and for a multi-valued lookup, whose values are - * read from its target table without the request's filters or container filter. + * column allows and some may match no row. * @param distinctCount COUNT(DISTINCT), known even when values is null. Counted in SQL, so unlike values it * includes blank strings and does not collapse numerically equal text; expect it to exceed * values.size() by a little rather than treating a difference as truncation. From 2e134b12ce7212de6dc3cf3d261e98c85682f731 Mon Sep 17 00:00:00 2001 From: XingY Date: Mon, 16 Nov 2026 16:32:49 -0800 Subject: [PATCH 4/7] Code review changes --- .../suggestions/FilterSuggestionService.java | 37 +++++++++++++------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java index 9cb2630b799..855562ef7f8 100644 --- a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java +++ b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java @@ -58,6 +58,8 @@ import java.util.Set; import java.util.function.Function; +import static org.labkey.api.data.DataRegionSelection.MAX_QUERY_SELECTION_SIZE; + /** Backs query-getFilterSuggestions.api: resolves the table, describes its candidate columns, and ranks suggestions. */ public class FilterSuggestionService { @@ -65,8 +67,6 @@ public class FilterSuggestionService private static final int MAX_SUGGESTIONS_LIMIT = 100; private static final String FILTER_REGION = "query"; private static final String ALL_COLUMNS = "*"; - // Matches the row count at which a grid stops counting exactly and shows "100,000+" - private static final long LARGE_TABLE_ROWS = 100_000; /** * @param columns the grid's display column fieldKeys @@ -236,7 +236,24 @@ public record ColumnFacet( @Nullable Long distinctCount, boolean truncated, boolean hasBlank - ) {} + ) + { + /** The facts this endpoint discloses, narrowed from everything the load gathered about the column. */ + static ColumnFacet of(@NotNull SuggestionColumn column) + { + return new ColumnFacet( + column.getFieldKey(), + column.getGridFieldKey(), + column.getType().name(), + column.getValues(), + // A multi-valued lookup's values come from its target table, unscoped by this request + column.isValuesFromData() && !column.isMultiValued(), + column.getDistinctCount(), + column.isValuesTruncated(), + column.isValuesHaveBlank() + ); + } + } /** * @param largeTable the table behind the query holds more rows than any grid would list values for. A coarse @@ -252,14 +269,9 @@ public record ColumnFacetsResponse(@NotNull List columns, boolean l Filled filled = describeAndFill(user, container, request, resolved); Long estimate = resolved.readsData() ? getProvisionedRowCount(resolved.table()) : null; - boolean largeTable = estimate != null && estimate > LARGE_TABLE_ROWS; + boolean largeTable = estimate != null && estimate > MAX_QUERY_SELECTION_SIZE; - List facets = filled.columns().stream() - .map(c -> new ColumnFacet(c.getFieldKey(), c.getGridFieldKey(), c.getType().name(), c.getValues(), - // A multi-valued lookup's values come from its target table, unscoped by this request - c.isValuesFromData() && !c.isMultiValued(), - c.getDistinctCount(), c.isValuesTruncated(), c.isValuesHaveBlank())) - .toList(); + List facets = filled.columns().stream().map(ColumnFacet::of).toList(); // Nothing was read, so the facts say nothing about the data; don't let a caller read that as "no values". // A failed load reads the same way: its column reports no values, which is not the same as having none. @@ -298,8 +310,9 @@ private static void tagResponse(TableInfo table, int count, boolean complete) try { // reltuples is a float; cast in SQL because the selector has no getter for Float - SQLFragment sql = new SQLFragment("SELECT CAST(reltuples AS BIGINT) FROM pg_class WHERE oid = to_regclass(?)") - .add(schemaName + "." + tableName); + SQLFragment sql = SQLFragment.unsafe( + "SELECT CAST(reltuples AS BIGINT) FROM pg_class WHERE oid = to_regclass(quote_ident(?) || '.' || quote_ident(?))", + schemaName, tableName); Long estimate = new SqlSelector(scope, sql).getObject(Long.class); // -1 means never analyzed in Postgres 14 and later; older versions report 0, indistinguishable from empty return estimate == null || estimate < 0 ? null : estimate; From 58dc28b58112a3392930e1278409664ec9dd8420 Mon Sep 17 00:00:00 2001 From: XingY Date: Mon, 16 Nov 2026 22:32:21 -0800 Subject: [PATCH 5/7] fix bad lookup query --- .../query/suggestions/ColumnFactsLoader.java | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java index 217331ca570..66355cfa512 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java @@ -94,19 +94,48 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag return stats; } + /** + * The column plus the lookup columns it is reached through. A display column's join reads its FK's base column, + * and a query selects only the columns asked for, so requesting the display column alone leaves the join + * pointing at one the inner select dropped. + */ + private static List withAncestors(QueryService service, TableInfo table, ColumnInfo column) + { + FieldKey parent = column.getFieldKey().getParent(); + if (parent == null) + return List.of(column); + + List ancestors = new ArrayList<>(); + for (FieldKey key = parent; key != null; key = key.getParent()) + ancestors.add(key); + + Map resolved = service.getColumns(table, ancestors); + List columns = new ArrayList<>(); + ancestors.forEach(key -> { + ColumnInfo ancestor = resolved.get(key); + if (ancestor != null) + columns.add(ancestor); + }); + // Last, and the instance the caller passed: the outer select reads values by this column's own alias + columns.add(column); + return columns; + } + @Override public @NotNull ColumnFact.Values loadValues(@NotNull TableInfo table, @NotNull ColumnInfo column, @NotNull SuggestionColumn.Type type, @NotNull Map parameters, @Nullable SimpleFilter filter) { QueryService service = QueryService.get(); QueryLogging queryLogging = new QueryLogging(); SQLFragment selectSql = service.getSelectBuilder(table) - .columns(List.of(column)) + .columns(withAncestors(service, table, column)) .filter(filter) .queryLogging(queryLogging) .distinct(true) .buildSqlFragment(); - SQLFragment sql = new SQLFragment("SELECT S.").appendIdentifier(column.getAlias()).append(" AS value FROM (") + // Distinct again out here: the inner one covers every column it projects, which for a lookup includes the + // base column the join reads, so two base values sharing a display value would each yield a row + SQLFragment sql = new SQLFragment("SELECT DISTINCT S.").appendIdentifier(column.getAlias()).append(" AS value FROM (") .append(selectSql) .append(") S"); // Two extra rows for a null and a blank value, which are dropped, and one to detect overflow From 8903db0c0dd32b213826e15bc34915798006e9ac Mon Sep 17 00:00:00 2001 From: XingY Date: Tue, 17 Nov 2026 12:15:45 -0800 Subject: [PATCH 6/7] reduce scope --- .../query/suggestions/ColumnFactsCache.java | 39 +++++++++---------- .../suggestions/FilterSuggestionService.java | 24 ++++++++++-- 2 files changed, 40 insertions(+), 23 deletions(-) diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java index c12235e78d4..cf973c29889 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java @@ -270,7 +270,7 @@ public FillResult fill(@NotNull FilterSuggestionContext context, @Nullable Map plans = new ArrayList<>(); for (SuggestionColumn column : described.columns()) { - if (described.auditLogged().contains(column)) + if (described.auditLogged().contains(column) || isThroughLookup(column) || described.lookups().containsKey(column)) continue; Scope columnScope = userScope; if (isShared(column)) @@ -336,6 +336,16 @@ private static void tagRequest(int columns, int pending, int failed, boolean bud TracedOperation.tagActiveSpan("labkey.suggestion.budget_exhausted", budgetExhausted); } + /** + * Whether the column's values are read through a lookup join, whose base column the query is free to prune: that + * has produced invalid SQL against nested queries, so the column falls back to the grid's own value query. + */ + private static boolean isThroughLookup(SuggestionColumn column) + { + ColumnInfo info = column.getColumnInfo(); + return info != null && info.getFieldKey().getParent() != null; + } + /** Whether the column's facts can follow the table's token, which shares them across users */ private static boolean isShared(SuggestionColumn column) { @@ -992,17 +1002,20 @@ public void testSharingFollowsToken() } @Test - public void testLookupDataIsNotShared() + public void testLookupColumnsAreNotRead() { - ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(0)); + TestSource source = new TestSource(0); + ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, source); TableInfo table = getTable(SAMPLE_TYPE); String email = "CreatedBy/Email"; - FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of(email)); + FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("CreatedBy", email)); assertTrue(byFieldKey(described).containsKey(email)); assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); - assertNotNull(cache.peek(context(table, _user), "shared", false, "values", email)); - assertNull("The table's token doesn't cover data reached through a lookup", cache.peek(context(table, UserManager.getGuestUser()), "shared", true, "values", email)); + assertEquals("A lookup's values are read through a join the query may prune", 0, source._calls.get()); + for (SuggestionColumn column : described.columns()) + assertNull(column.getFieldKey(), column.getValues()); + assertNull(cache.peek(context(table, _user), "shared", false, "values", email)); } @Test @@ -1030,20 +1043,6 @@ public void testCalculatedDataIsNotShared() assertNull("A calculated value can depend on the user", cache.peek(context(table, UserManager.getGuestUser()), "shared", true, "values", "viewer")); } - @Test - public void testLookupValuesComeFromRows() - { - ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(0)); - TableInfo table = getTable(SAMPLE_TYPE); - FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("CreatedBy", "ModifiedBy")); - assertEquals(2, described.columns().size()); - assertTrue(described.lookups().isEmpty()); - - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); - for (SuggestionColumn column : described.columns()) - assertEquals(column.getFieldKey(), List.of(_user.getDisplayName(_user)), column.getValues()); - } - @Test public void testGridFieldKeyIsTheRequestedColumn() { diff --git a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java index 855562ef7f8..ade9affd691 100644 --- a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java +++ b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java @@ -38,6 +38,7 @@ import org.labkey.api.query.QueryForm; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainKind; +import org.labkey.api.exp.query.SamplesSchema; import org.labkey.api.query.QueryService; import org.labkey.api.query.UserSchema; import org.labkey.api.query.suggestions.FilterSuggestionContext; @@ -179,9 +180,17 @@ private static Filled describeAndFill(@NotNull User user, @NotNull Container con { if (resolved.readsData()) { - ColumnFactsCache.FillResult result = ColumnFactsCache.get().fill(context, request.parameters(), resolved.filter(), described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); - complete &= result.complete(); - failed = result.failed(); + if (hasChangeTokens(table)) + { + ColumnFactsCache.FillResult result = ColumnFactsCache.get().fill(context, request.parameters(), resolved.filter(), described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); + complete &= result.complete(); + failed = result.failed(); + } + else + { + // Nothing was read, so don't let a caller read the columns' absent facts as "no values" + complete = false; + } } } catch (RuntimeException e) @@ -324,6 +333,15 @@ private static void tagResponse(TableInfo table, int count, boolean complete) } } + /** + * Whether a data change to the table moves a change token, which every cached fact is keyed by. Only sample tables + * supply one, so facts read from anything else would be served stale until they aged out. + */ + private static boolean hasChangeTokens(TableInfo table) + { + return SamplesSchema.SCHEMA_NAME.equalsIgnoreCase(table.getPublicSchemaName()); + } + /** The first non-null token from a provider that handles the table; null keeps its facts per user. */ private static @Nullable String getChangeToken(TableInfo table) { From 6cd338618708b539800d49e1e6fd768630f6bb34 Mon Sep 17 00:00:00 2001 From: XingY Date: Fri, 20 Nov 2026 08:38:09 -0800 Subject: [PATCH 7/7] merge in 8368 --- .../org/labkey/api/data/TableSelector.java | 105 ++++++++++---- .../query/suggestions/ColumnFactsLoader.java | 129 ++++++++++-------- 2 files changed, 153 insertions(+), 81 deletions(-) diff --git a/api/src/org/labkey/api/data/TableSelector.java b/api/src/org/labkey/api/data/TableSelector.java index 3bada4b5cc3..a3c5e7484a9 100644 --- a/api/src/org/labkey/api/data/TableSelector.java +++ b/api/src/org/labkey/api/data/TableSelector.java @@ -564,6 +564,26 @@ public Map> getAggregates(final List aggregates) * @param maxCount when > 0 and the only aggregate is COUNT(*), bounds the inner select to maxCount + 1 rows so the database can stop early. */ public Map> getAggregates(final List aggregates, int maxCount) + { + // Results already arrive keyed by FieldKey, so only the String conversion needs to be removed in order + // to support a return type of Map>. + Map> results = new CaseInsensitiveHashMap<>(); + prepareAggregates(aggregates, maxCount) + .execute() + .forEach((fieldKey, fieldResults) -> results.put(fieldKey.toString(), fieldResults)); + return results; + } + + public PreparedAggregates prepareAggregates(final List aggregates) + { + return prepareAggregates(aggregates, 0); + } + + /** + * Generates the aggregate SQL now and runs it on {@link PreparedAggregates#execute()}, so a caller can serialize SQL generation without holding a lock while the query runs. + * @param maxCount when > 0 and the only aggregate is COUNT(*), bounds the inner select to maxCount + 1 rows so the database can stop early. + */ + public PreparedAggregates prepareAggregates(final List aggregates, int maxCount) { // If we are only asking for the COUNT(*) aggregate, then we don't need to include all of the table columns in the subselect. // This can make a big performance difference for Sample Type and Data Class tables as they can then skip @@ -571,8 +591,7 @@ public Map> getAggregates(final List aggregates, boolean countStarOnly = aggregates.size() == 1 && aggregates.getFirst().isCountStar(); Collection aggColumns = countStarOnly ? getRowCountingSelectColumns(_table) : _columns; - final AggregateSqlFactory sqlFactory = new AggregateSqlFactory(_filter, aggregates, aggColumns); - ResultSetFactory resultSetFactory = new ExecutingResultSetFactory(sqlFactory); + AggregateSqlFactory sqlFactory = new AggregateSqlFactory(_filter, aggregates, aggColumns); // Setting _maxRows threads LIMIT maxCount + 1 through TableSqlFactory.getSql() into the inner select; restore it after. boolean cap = maxCount > 0 && countStarOnly; @@ -582,37 +601,75 @@ public Map> getAggregates(final List aggregates, try { - return resultSetFactory.handleResultSet((rs, conn) -> { - Map> results = new CaseInsensitiveHashMap<>(); + return new PreparedAggregates(aggregates, sqlFactory._columnMap, sqlFactory.getSql(), sqlFactory.getStatementMaxRows()); + } + finally + { + if (cap) + _maxRows = maxRows; + } + } + + /** Aggregate SQL generated by {@link #prepareAggregates(List, int)}, run against this selector's scope and settings. */ + public class PreparedAggregates + { + private final List _aggregates; + private final Map _columnMap; + private final @Nullable SQLFragment _sql; + private final @Nullable Integer _statementMaxRows; + + private PreparedAggregates(List aggregates, Map columnMap, @Nullable SQLFragment sql, @Nullable Integer statementMaxRows) + { + _aggregates = aggregates; + _columnMap = columnMap; + _sql = sql; + _statementMaxRows = statementMaxRows; + } + + /** Null when no aggregate applies to its column, in which case {@link #execute()} returns an empty map without querying. */ + public @Nullable SQLFragment getSql() + { + return _sql; + } - // null == rs is the short-circuit case... SqlFactory didn't find any aggregate columns, so - // query wasn't executed. Just return an empty map in this case. - if (null != rs) + public Map> execute() + { + SqlFactory sqlFactory = new BaseSqlFactory() { - // Issue 17536: Issue a warning instead of blowing up if there is no result row containing the aggregate values. - if (!rs.next()) + @Override + public @Nullable SQLFragment getSql() { - LOG.warn("Expected a non-empty resultset from aggregate query."); + return _sql; } - else + + @Override + public @Nullable Integer getStatementMaxRows() { - for (Aggregate agg : aggregates) - { - if (!results.containsKey(agg.getFieldKey().toString())) - results.put(agg.getFieldKey().toString(), new ArrayList<>()); + return _statementMaxRows; + } + }; + + return new ExecutingResultSetFactory(sqlFactory).handleResultSet((rs, _) -> { + Map> results = new LinkedHashMap<>(); - results.get(agg.getFieldKey().toString()).add(agg.getResult(rs, sqlFactory._columnMap, getScope().getSqlDialect())); + // null == rs is the short-circuit case... SqlFactory didn't find any aggregate columns, so + // query wasn't executed. Just return an empty map in this case. + if (null != rs) + { + // Issue 17536: Issue a warning instead of blowing up if there is no result row containing the aggregate values. + if (!rs.next()) + { + LOG.warn("Expected a non-empty resultset from aggregate query."); + } + else + { + for (Aggregate agg : _aggregates) + results.computeIfAbsent(agg.getFieldKey(), _ -> new ArrayList<>()).add(agg.getResult(rs, _columnMap, getScope().getSqlDialect())); } } - } - return results; - }); - } - finally - { - if (cap) - _maxRows = maxRows; + return results; + }); } } diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java index 66355cfa512..849d45553ab 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java @@ -20,7 +20,6 @@ import org.labkey.api.data.Aggregate; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.QueryLogging; -import org.labkey.api.data.Results; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.Sort; @@ -32,7 +31,6 @@ import org.labkey.api.query.suggestions.SuggestionColumn; import java.math.BigDecimal; -import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; @@ -74,15 +72,22 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag byFieldKey.put(fieldKey, new Aggregates(min, max, distinct)); } - Map> results = new TableSelector(table, columns, filter, null) - .setNamedParameters(parameters) - .setQueryTimeout(QUERY_TIMEOUT_SECONDS) - .getAggregates(aggregates); + TableSelector.PreparedAggregates prepared; + // Parallel loads share this table; hold it only while generating SQL so scans run concurrently + // noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (table) + { + prepared = new TableSelector(table, columns, filter, null) + .setNamedParameters(parameters) + .setQueryTimeout(QUERY_TIMEOUT_SECONDS) + .prepareAggregates(aggregates); + } + Map> results = prepared.execute(); Map stats = new HashMap<>(); byFieldKey.forEach((fieldKey, aggs) -> { // Absent when the aggregate doesn't apply to the column's type; the caller records that as a failure - List columnResults = results.get(fieldKey.toString()); + List columnResults = results.get(fieldKey); if (columnResults == null) return; Object rawMin = getValue(columnResults, aggs.min()); @@ -94,44 +99,52 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag return stats; } - /** - * The column plus the lookup columns it is reached through. A display column's join reads its FK's base column, - * and a query selects only the columns asked for, so requesting the display column alone leaves the join - * pointing at one the inner select dropped. - */ - private static List withAncestors(QueryService service, TableInfo table, ColumnInfo column) - { - FieldKey parent = column.getFieldKey().getParent(); - if (parent == null) - return List.of(column); - - List ancestors = new ArrayList<>(); - for (FieldKey key = parent; key != null; key = key.getParent()) - ancestors.add(key); - - Map resolved = service.getColumns(table, ancestors); - List columns = new ArrayList<>(); - ancestors.forEach(key -> { - ColumnInfo ancestor = resolved.get(key); - if (ancestor != null) - columns.add(ancestor); - }); - // Last, and the instance the caller passed: the outer select reads values by this column's own alias - columns.add(column); - return columns; - } + // Temporarily disabled to test platform PR #8368 in isolation +// /** +// * The column plus the lookup columns it is reached through. A display column's join reads its FK's base column, +// * and a query selects only the columns asked for, so requesting the display column alone leaves the join +// * pointing at one the inner select dropped. +// */ +// private static List withAncestors(QueryService service, TableInfo table, ColumnInfo column) +// { +// FieldKey parent = column.getFieldKey().getParent(); +// if (parent == null) +// return List.of(column); +// +// List ancestors = new ArrayList<>(); +// for (FieldKey key = parent; key != null; key = key.getParent()) +// ancestors.add(key); +// +// Map resolved = service.getColumns(table, ancestors); +// List columns = new ArrayList<>(); +// ancestors.forEach(key -> { +// ColumnInfo ancestor = resolved.get(key); +// if (ancestor != null) +// columns.add(ancestor); +// }); +// // Last, and the instance the caller passed: the outer select reads values by this column's own alias +// columns.add(column); +// return columns; +// } @Override public @NotNull ColumnFact.Values loadValues(@NotNull TableInfo table, @NotNull ColumnInfo column, @NotNull SuggestionColumn.Type type, @NotNull Map parameters, @Nullable SimpleFilter filter) { QueryService service = QueryService.get(); QueryLogging queryLogging = new QueryLogging(); - SQLFragment selectSql = service.getSelectBuilder(table) - .columns(withAncestors(service, table, column)) - .filter(filter) - .queryLogging(queryLogging) - .distinct(true) - .buildSqlFragment(); + SQLFragment selectSql; + // Parallel loads share this table; hold it only while generating SQL so scans run concurrently + // noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (table) + { + selectSql = service.getSelectBuilder(table) +// .columns(withAncestors(service, table, column)) + .columns(column) + .filter(filter) + .queryLogging(queryLogging) + .distinct(true) + .buildSqlFragment(); + } // Distinct again out here: the inner one covers every column it projects, which for a lookup includes the // base column the join reads, so two base values sharing a display value would each yield a row @@ -175,27 +188,29 @@ private static List withAncestors(QueryService service, TableInfo ta Map> shapes = new LinkedHashMap<>(); columns.forEach(column -> shapes.put(column.getFieldKey(), new LinkedHashSet<>())); - TableSelector selector = new TableSelector(table, columns, filter, getNewestFirstSort(table)) - .setMaxRows(SHAPE_SAMPLE_SIZE) - .setNamedParameters(parameters) - .setQueryTimeout(QUERY_TIMEOUT_SECONDS); - try (Results results = selector.getResults(false)) + Sort sort = getNewestFirstSort(table); + SqlSelector selector; + // Parallel loads share this table; hold it only while generating SQL so scans run concurrently + // noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (table) { - while (results.next()) + selector = QueryService.get().getSelectBuilder(table) + .columns(columns) + .filter(filter) + .sort(sort) + .maxRows(SHAPE_SAMPLE_SIZE) + .forceSort(true) + .buildSqlSelector(parameters); + } + selector.setQueryTimeout(QUERY_TIMEOUT_SECONDS).forEach(rs -> { + for (ColumnInfo column : columns) { - for (Map.Entry> entry : shapes.entrySet()) - { - Object value = results.getObject(entry.getKey()); - String text = value == null ? null : value.toString(); - if (text != null && !text.isBlank() && text.length() <= MAX_VALUE_LENGTH) - entry.getValue().add(FilterSuggestionRanker.getValueShape(text)); - } + Object value = rs.getObject(column.findColumn(rs)); + String text = value == null ? null : value.toString(); + if (text != null && !text.isBlank() && text.length() <= MAX_VALUE_LENGTH) + shapes.get(column.getFieldKey()).add(FilterSuggestionRanker.getValueShape(text)); } - } - catch (SQLException e) - { - throw new RuntimeException(e); - } + }); Map result = new HashMap<>(); shapes.forEach((fieldKey, columnShapes) -> result.put(fieldKey, new ColumnFact.Shapes(List.copyOf(columnShapes))));