πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(filters): deselecting a facet value excludes it instead of selecting the complement (LFE-10717) (#14939)
Nikita Kabardinb3f97a00615a
diff --git a/web/src/components/table/data-table-controls.clienttest.tsx b/web/src/components/table/data-table-controls.clienttest.tsxindex 81a532e3c3..a2d03f6978 100644--- a/web/src/components/table/data-table-controls.clienttest.tsx+++ b/web/src/components/table/data-table-controls.clienttest.tsx@@ -146,6 +146,49 @@ describe("CategoricalFacet", () => {expect(screen.getAllByRole("checkbox").length).toBeLessThanOrEqual(12);});+ it("pins the excluded (unchecked) options to the top for none-of filters (LFE-10717)", () => {+ // Under the checked=kept model a `none of [opt-18]` exclusion reports+ // every option EXCEPT opt-18 as selected. The applied filter β the thing+ // LFE-10494 pinning exists to surface β is the excluded value, so it must+ // be pinned above the kept options instead of sinking below the cap.+ const options = Array.from({ length: 20 }, (_, i) => `opt-${i}`);+ const value = options.filter((option) => option !== "opt-18");+ render(+ <Accordion type="multiple" value={["c"]}>+ <CategoricalFacet+ label="C"+ filterKey="c"+ expanded+ loading={false}+ options={options}+ counts={new Map()}+ value={value}+ operator="none of"+ onOperatorChange={() => {}}+ onChange={() => {}}+ isActive+ isDisabled={false}+ onReset={() => {}}+ />+ </Accordion>,+ );++ // The cap still applies...+ expect(+ screen.getByRole("button", { name: "Show more values" }),+ ).toBeInTheDocument();++ // ...yet the excluded value is visible despite sitting at position 19,+ // and it precedes the first kept option in DOM order (pinned to top).+ const excluded = screen.getByText("opt-18");+ const firstKept = screen.getByText("opt-0");+ expect(excluded).toBeInTheDocument();+ expect(+ excluded.compareDocumentPosition(firstKept) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });+it("does not reorder short, fully-visible lists", () => {render(<Accordion type="multiple" value={["c"]}>diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex e849c0377e..eb20c3dde4 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -742,29 +742,41 @@ export function CategoricalFacet({}): visibleOptionValues;- // Order a genuine selection to the top of the list so an applied filter is- // immediately visible β without scrolling or expanding "Show more" β even- // when the selected value sits far down a long list (LFE-10494).+ // Order the applied filter to the top of the list so it is immediately+ // visible β without scrolling or expanding "Show more" β even when its+ // value sits far down a long list (LFE-10494). The rows carrying the+ // applied filter are the CHECKED values for a positive selection, but the+ // UNCHECKED (excluded) values for a `none of` filter: under the+ // checked=kept display model the checked set is the complement of the+ // exclusions (LFE-10717), and pinning that complement would sink the+ // just-unchecked row below the cap.//// Two guards keep this honest:// 1. Only reorder long lists (more options than the cap) that carry a real,// strict-subset selection. `value` mirrors the hook's// `computeSelectedValues`, which reports EVERY option as "selected" when- // no filter is applied (and the inverted set for `none of`). Requiring a- // strict subset skips that all-selected default β otherwise the whole- // list would be treated as pinned β and leaves short lists untouched.+ // no filter is applied (and the kept complement for `none of`).+ // Requiring a strict subset skips that all-selected default β otherwise+ // the whole list would be treated as pinned β and leaves short lists+ // untouched.// 2. The visible-count cap is applied to the COMBINED ordered list, so even- // a large selection (many values, or a `none of` include-set) can never- // render the entire list; "Show more" still gates the overflow.+ // a large pinned set (many selected values, or many exclusions) can+ // never render the entire list; "Show more" still gates the overflow.const selectedSet = new Set(value);- const pinSelected =+ const pinnedSet =+ operator === "none of"+ ? new Set(+ visibleOptionValues.filter((option) => !selectedSet.has(option)),+ )+ : selectedSet;+ const pinApplied =hasMoreOptions &&value.length > 0 &&value.length < visibleOptionValues.length;- const orderedOptions = pinSelected+ const orderedOptions = pinApplied? [- ...filteredOptions.filter((option) => selectedSet.has(option)),- ...filteredOptions.filter((option) => !selectedSet.has(option)),+ ...filteredOptions.filter((option) => pinnedSet.has(option)),+ ...filteredOptions.filter((option) => !pinnedSet.has(option)),]: filteredOptions;@@ -773,13 +785,13 @@ export function CategoricalFacet({? orderedOptions: orderedOptions.slice(0, MAX_VISIBLE_OPTIONS);- // Split the visible slice so a separator can mark where the pinned selection- // ends. When not pinning, everything renders in natural order (no divider).- const visibleSelectedOptions = pinSelected- ? visibleOptions.filter((option) => selectedSet.has(option))+ // Split the visible slice so a separator can mark where the pinned rows+ // end. When not pinning, everything renders in natural order (no divider).+ const visiblePinnedOptions = pinApplied+ ? visibleOptions.filter((option) => pinnedSet.has(option)): [];- const visibleRemainingOptions = pinSelected- ? visibleOptions.filter((option) => !selectedSet.has(option))+ const visibleRemainingOptions = pinApplied+ ? visibleOptions.filter((option) => !pinnedSet.has(option)): visibleOptions;const renderOption = (option: string) => {@@ -831,13 +843,21 @@ export function CategoricalFacet({It allows switching between the supported array matching modes:- SOME: Match items with ANY selected value (OR logic)- ALL: Match items with ALL selected values (AND logic)- - NONE: Exclude items with ANY selected value-- The toggle is shown whenever useSidebarFilterState exposes operator controls- for an arrayOptions column, including before any values are selected so users- can persist an operator preference first. Other filter types (stringOptions,- boolean, numeric) don't get this toggle because these array-specific modes- are not semantically meaningful there.+ - NONE: Exclude items carrying any UNCHECKED value (the filter+ stores the exclusions; checkboxes show the kept complement,+ LFE-10717)++ Toggling between modes carries the stored value list over, so+ SOME "match a or b" becomes NONE "exclude a and b" β the+ checked set visually flips to its complement.++ NONE mode usually engages by itself: unchecking a value from+ the all-checked default persists `none of [value]`. The toggle+ remains for converting an existing selection or persisting an+ operator preference before any values are selected. Other+ filter types (stringOptions, boolean, numeric) don't get this+ toggle because these array-specific modes are not semantically+ meaningful there.Currently enabled for:- Traces: tags@@ -967,11 +987,12 @@ export function CategoricalFacet({</div>) : (<>- {/* Selected options, pinned to the top (long lists only) */}- {visibleSelectedOptions.map(renderOption)}+ {/* Applied-filter rows (selected, or excluded under+ `none of`), pinned to the top (long lists only) */}+ {visiblePinnedOptions.map(renderOption)}- {/* Separator between the pinned selection and the rest */}- {visibleSelectedOptions.length > 0 &&+ {/* Separator between the pinned rows and the rest */}+ {visiblePinnedOptions.length > 0 &&visibleRemainingOptions.length > 0 && (<divclassName="border-border/60 mx-3 my-1 border-t"@@ -979,7 +1000,7 @@ export function CategoricalFacet({/>)}- {/* Remaining (unselected) options, capped */}+ {/* Remaining options, capped */}{visibleRemainingOptions.map(renderOption)}{hasMoreFilteredOptions && !showAll && (<div className="px-2">diff --git a/web/src/features/filters/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.tsindex 2308fa1091..3b7e5580d3 100644--- a/web/src/features/filters/filter-integration.clienttest.ts+++ b/web/src/features/filters/filter-integration.clienttest.ts@@ -885,36 +885,103 @@ describe("resolveCheckboxOperator (arrayOptions vs stringOptions)", () => {const availableValues = ["tag-1", "tag-2", "tag-3", "tag-4", "tag-5"];describe("arrayOptions (e.g., tags)", () => {- it('should use "any of" with selected values when no existing filter', () => {+ it('converts a deselect-from-implicit-all into "none of [deselected]" (LFE-10717)', () => {+ // No existing filter = the facet renders every option checked. Unchecking+ // tag-3 means "exclude tag-3". For a multi-valued column that is only+ // expressible as `none of [tag-3]` β `any of [remaining]` still matches+ // rows carrying tag-3 alongside another tag, and materializes+ // O(option-count) state into the URL (HTTP 431 at ~1000 user IDs).const result = resolveCheckboxOperator({colType: "arrayOptions",existingFilter: undefined,- values: ["tag-1", "tag-2"],+ values: ["tag-1", "tag-2", "tag-4", "tag-5"],availableValues,});expect(result).toEqual({- finalOperator: "any of",- finalValues: ["tag-1", "tag-2"],+ finalOperator: "none of",+ finalValues: ["tag-3"],});});- it('should preserve "none of" for arrayOptions', () => {+ it('accumulates exclusions while a "none of" filter is active', () => {+ // The facet shows the kept set (all-but-excluded checked); unchecking+ // another value grows the exclusion list.const result = resolveCheckboxOperator({colType: "arrayOptions",existingFilter: {column: "tags",type: "arrayOptions",operator: "none of",- value: ["tag-3", "tag-4", "tag-5"],+ value: ["tag-3"],},- values: ["tag-1", "tag-2"],+ values: ["tag-1", "tag-2", "tag-5"],availableValues,});expect(result).toEqual({finalOperator: "none of",- finalValues: ["tag-1", "tag-2"],+ finalValues: ["tag-3", "tag-4"],+ });+ });++ it("drops an exclusion when its value is re-checked", () => {+ const result = resolveCheckboxOperator({+ colType: "arrayOptions",+ existingFilter: {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-3", "tag-4"],+ },+ values: ["tag-1", "tag-2", "tag-3", "tag-5"],+ availableValues,+ });++ expect(result).toEqual({+ finalOperator: "none of",+ finalValues: ["tag-4"],+ });+ });++ it("preserves exclusions that fell out of the current option list", () => {+ // An excluded value can drop out of the top-N-capped / time-scoped+ // option list; interacting with other checkboxes must not silently+ // resurrect it.+ const result = resolveCheckboxOperator({+ colType: "arrayOptions",+ existingFilter: {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["stale-tag"],+ },+ values: ["tag-1", "tag-2", "tag-4", "tag-5"],+ availableValues,+ });++ expect(result).toEqual({+ finalOperator: "none of",+ finalValues: ["stale-tag", "tag-3"],+ });+ });++ it('returns an empty "none of" when every exclusion is re-checked (caller clears the filter)', () => {+ const result = resolveCheckboxOperator({+ colType: "arrayOptions",+ existingFilter: {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-3"],+ },+ values: availableValues,+ availableValues,+ });++ expect(result).toEqual({+ finalOperator: "none of",+ finalValues: [],});});@@ -992,6 +1059,28 @@ describe("resolveCheckboxOperator (arrayOptions vs stringOptions)", () => {});});+ it("preserves exclusions that fell out of the current option list (parity with arrayOptions)", () => {+ // stringOptions option lists are top-N-capped / filter-scoped too; an+ // invisible exclusion cannot have been re-checked and must survive+ // other checkbox interactions.+ const result = resolveCheckboxOperator({+ colType: "stringOptions",+ existingFilter: {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["stale-name"],+ },+ values: ["tag-1", "tag-2", "tag-4", "tag-5"],+ availableValues,+ });++ expect(result).toEqual({+ finalOperator: "none of",+ finalValues: ["stale-name", "tag-3"],+ });+ });+it('should use "any of" when existing filter is "any of" for stringOptions', () => {const result = resolveCheckboxOperator({colType: "stringOptions",@@ -1014,13 +1103,26 @@ describe("resolveCheckboxOperator (arrayOptions vs stringOptions)", () => {});describe("computeSelectedValues", () => {- it('should keep excluded values checked for arrayOptions "none of" filters', () => {+ it('inverts arrayOptions "none of" into the kept set, like stringOptions (LFE-10717)', () => {+ // Unified checked=kept display model: a `none of [tag-2]` exclusion+ // renders as everything-but-tag-2 checked, so the deselect gesture+ // round-trips (uncheck tag-2 β none of [tag-2] β tag-2 shown unchecked).const result = computeSelectedValues(["tag-1", "tag-2", "tag-3"], {type: "arrayOptions",operator: "none of",value: ["tag-2"],});+ expect(result).toEqual(["tag-1", "tag-3"]);+ });++ it('keeps arrayOptions "any of" selections as-is', () => {+ const result = computeSelectedValues(["tag-1", "tag-2", "tag-3"], {+ type: "arrayOptions",+ operator: "any of",+ value: ["tag-2"],+ });+expect(result).toEqual(["tag-2"]);});diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex 29f79348a7..03c0ccfc49 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -15,6 +15,7 @@ import {computeSelectedValues,encodeFiltersGeneric,decodeFiltersGeneric,+ MAX_URL_FILTER_QUERY_LENGTH,} from "../lib/filter-query-encoding";import {buildSidebarFilterQueryStorageKey,@@ -156,11 +157,12 @@ export interface CategoricalUIFilter extends BaseUIFilter {/** Optional function to render an icon next to filter option labels */renderIcon?: (value: string) => React.ReactNode;/**- * Current operator for arrayOptions columns (tags, labels, etc.)+ * Current operator of the facet's checkbox filter (arrayOptions AND+ * stringOptions columns; undefined when no filter is applied):* - "any of": OR logic - match if item has ANY selected value- * - "all of": AND logic - match if item has ALL selected values- * - "none of": exclude items with ANY selected value- * undefined for non-arrayOptions columns+ * - "all of": AND logic - match if item has ALL selected values (arrayOptions only)+ * - "none of": exclude items carrying an UNCHECKED value (the filter stores+ * the exclusions; checkboxes display the kept complement)*/operator?: "any of" | "all of" | "none of";/**@@ -393,20 +395,40 @@ const DEFAULT_HOOK_OPTIONS: UseSidebarFilterStateOptions = {stateLocation: "urlAndSessionStorage",};+// The URL value a given serialized filter query should produce: oversized+// queries stay out of the URL entirely β the full request head is capped at+// ~16KB by Node and most proxies, so a giant `?filter=` 431s on the next full+// request (LFE-10717). Callers fall back to the session-storage mirror, which+// keeps same-tab refreshes working. Only used where that fallback exists+// (stateLocation "urlAndSessionStorage").+const toUrlFilterQuery = (encoded: string): string =>+ encoded.length > MAX_URL_FILTER_QUERY_LENGTH ? "" : encoded;+/*** Pure function that determines the operator and values for checkbox-based* filter interactions. Extracted for testability.*- * For arrayOptions (e.g., tags), "none of" inversion is NOT semantically- * equivalent because a single trace can have multiple tags. For example,- * a trace with tags [tag-1, tag-3] matches "any of [tag-1, tag-2]" but does NOT match- * "none of [tag-3, tag-4, tag-5]" (because it contains tag-3). Because of that, we never- * derive array filters by inverting the deselected set. Instead, we keep the user's explicit- * array operator when one already exists ("all of" / "none of"), and otherwise default new- * checkbox selections to positive matching ("any of").+ * Checkboxes always show the KEPT set β "no filter" renders every option+ * checked (implicit all). Unchecking from that state therefore expresses an+ * exclusion, and the deselected values persist as `none of [deselected]`+ * (LFE-10717). Materializing the complement (`any of [remaining]`) instead is+ * wrong twice over for multi-valued columns (arrayOptions): a row carrying an+ * excluded value alongside a still-checked one keeps matching (a session with+ * users [X, Y] matches "any of [everyone-but-X]" via Y), and the complement is+ * O(option-count) β at ~1000 user IDs it blows the URL budget (HTTP 431).+ *+ * An EXPLICIT positive selection is never inverted (a trace with tags+ * [tag-1, tag-3] matches "any of [tag-1, tag-2]" but not+ * "none of [tag-3, tag-4, tag-5]"): once an "any of" filter exists, checkbox+ * changes keep it positive, and "all of" is likewise preserved. While a+ * "none of" filter is active, the checked set is the complement of the stored+ * exclusions, so interactions re-derive the exclusions from what is unchecked+ * β carrying over exclusions that fell out of the (top-N-capped, time-scoped)+ * option list, which cannot have been re-checked while invisible.*- * For stringOptions (e.g., environment), each row has a single value,- * so "none of [deselected]" is semantically equivalent to "any of [selected]".+ * stringOptions (e.g., environment) behave the same way; each row has a+ * single value there, so "none of [deselected]" is exactly equivalent to+ * "any of [selected]".** @param params - Filter context including column type, existing filter, selected and available values* @returns Object with finalOperator and finalValues to apply@@ -430,7 +452,21 @@ export function resolveCheckboxOperator(params: {existingFilter?.operator === "none of" &&existingFilter.type === "arrayOptions") {- return { finalOperator: "none of", finalValues: values };+ const checked = new Set(values);+ const availableSet = new Set(availableValues);+ const carriedExclusions = existingFilter.value.filter(+ (v) => !availableSet.has(v),+ );+ const deselected = availableValues.filter((v) => !checked.has(v));+ return {+ finalOperator: "none of",+ finalValues: [...carriedExclusions, ...deselected],+ };+ }+ if (!existingFilter) {+ const checked = new Set(values);+ const deselected = availableValues.filter((v) => !checked.has(v));+ return { finalOperator: "none of", finalValues: deselected };}return { finalOperator: "any of", finalValues: values };}@@ -444,8 +480,18 @@ export function resolveCheckboxOperator(params: {existingFilter.operator === "none of" &&existingFilter.type === "stringOptions") {- const deselected = availableValues.filter((v) => !values.includes(v));- return { finalOperator: "none of", finalValues: deselected };+ // Same carry-over as the arrayOptions branch above: exclusions outside+ // the current option list are invisible and cannot have been re-checked.+ const checked = new Set(values);+ const availableSet = new Set(availableValues);+ const carriedExclusions = existingFilter.value.filter(+ (v) => !availableSet.has(v),+ );+ const deselected = availableValues.filter((v) => !checked.has(v));+ return {+ finalOperator: "none of",+ finalValues: [...carriedExclusions, ...deselected],+ };}return { finalOperator: "any of", finalValues: values };}@@ -709,8 +755,24 @@ export function useSidebarFilterState(}const encoded = encodeFiltersGeneric(explicitFilters);+ const urlQuery =+ stateLocationType === "urlAndSessionStorage"+ ? toUrlFilterQuery(encoded)+ : encoded;+ if (urlQuery !== encoded) {+ console.warn(+ `Filter state (${encoded.length} chars) exceeds the URL budget; persisting it in session storage only.`,+ );+ }setPendingFiltersQuery(encoded);- setUrlFiltersQuery(encoded || null, options?.updateType);+ // Eviction of an oversized state replaces the current history entry+ // regardless of the caller's updateType: repeated interactions in the+ // oversized regime must not push a stack of identical param-less+ // entries the Back button has to walk through.+ setUrlFiltersQuery(+ urlQuery || null,+ urlQuery !== encoded ? "replaceIn" : options?.updateType,+ );if (stateLocationType === "urlAndSessionStorage") {setStoredFiltersQuery(encoded);}@@ -735,7 +797,14 @@ export function useSidebarFilterState(if (pendingFiltersQuery === null) return;const normalizedUrlFiltersQuery = urlFiltersQuery ?? "";- if (normalizedUrlFiltersQuery === pendingFiltersQuery) {+ // An oversized pending query is intentionally never written to the URL;+ // it has "caught up" once the URL param is gone (state then reads from+ // the session-storage mirror).+ const expectedUrlFiltersQuery =+ stateLocationType === "urlAndSessionStorage"+ ? toUrlFilterQuery(pendingFiltersQuery)+ : pendingFiltersQuery;+ if (normalizedUrlFiltersQuery === expectedUrlFiltersQuery) {setPendingFiltersQuery(null);}}, [stateLocationType, pendingFiltersQuery, urlFiltersQuery]);@@ -757,12 +826,21 @@ export function useSidebarFilterState(if (pendingFiltersQuery !== null) return;if (typeof urlFiltersQuery === "string") {- if (urlFiltersQuery !== canonicalFiltersQuery) {+ // Canonicalization also evicts an oversized query that arrived via the+ // URL (e.g. a legacy complement-filter link): it moves to the+ // session-storage mirror instead of being rewritten into the URL.+ const canonicalUrlQuery =+ stateLocationType === "urlAndSessionStorage"+ ? toUrlFilterQuery(canonicalFiltersQuery)+ : canonicalFiltersQuery;+ if (urlFiltersQuery !== canonicalUrlQuery) {setPendingFiltersQuery(canonicalFiltersQuery);// replaceIn: sanitizing is a programmatic correction of the current// URL β pushing would mint a history entry holding the non-canonical// filter, which Back lands on and this effect re-fires (LFE-10715).- setUrlFiltersQuery(canonicalFiltersQuery || null, "replaceIn");+ // Same for evicting an oversized query (canonicalUrlQuery = ""):+ // pushing would turn Back into a rewrite loop on a legacy giant link.+ setUrlFiltersQuery(canonicalUrlQuery || null, "replaceIn");}if (@@ -885,28 +963,50 @@ export function useSidebarFilterState(let finalOperator: "any of" | "none of" | "all of";let finalValues: string[];const existingFilter = current.find((f) => f.column === column);- const preserveArrayNoneOfOperator =- colType === "arrayOptions" &&- existingFilter?.type === "arrayOptions" &&- existingFilter.operator === "none of";+ const isManagedEnvironmentColumn =+ column === managedEnvironmentColumn &&+ managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0;+ // For an active "none of" filter, "all checked" is not the same as+ // "no filter": exclusions outside the current option list may still be+ // live. Skip the all-selected removal shortcut and let+ // resolveCheckboxOperator re-derive the exclusion set (an emptied set is+ // removed below). For arrayOptions this also covers "none checked",+ // which means exclude-everything rather than reset; stringOptions keeps+ // its long-standing uncheck-everything-resets behavior. The managed+ // environment column is exempt: its all-selected shortcut persists the+ // explicit enable-all-environments override, and its hidden+ // environments are always listed, so there is nothing to carry.+ const preserveNoneOfOperator =+ (colType === "arrayOptions" &&+ existingFilter?.type === "arrayOptions" &&+ existingFilter.operator === "none of") ||+ (colType !== "arrayOptions" &&+ existingFilter?.type === "stringOptions" &&+ existingFilter.operator === "none of" &&+ values.length > 0 &&+ !isManagedEnvironmentColumn);if (operator !== undefined) {// Explicit operator provided (e.g., from "Only" button or operator toggle) - use as-isfinalOperator = operator;finalValues = values;++ // An empty "none of" excludes nothing: since deselecting from the+ // all-checked default now enters NONE mode by itself, toggling NONE+ // without a selection is a no-op rather than a persisted vacuous+ // filter (which would light the badge while matching everything).+ if (finalOperator === "none of" && finalValues.length === 0) {+ return other;+ }} else {// If all items selected or none selected, remove filter// (only for implicit/checkbox-based selection, not when operator is explicitly set)if (- !preserveArrayNoneOfOperator &&+ !preserveNoneOfOperator &&(values.length === 0 ||(values.length === availableValues.length &&availableValues.every((v) => values.includes(v))))) {- const isManagedEnvironmentColumn =- column === managedEnvironmentColumn &&- managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0;-// Keep explicit override when user intentionally enables all environments.if (isManagedEnvironmentColumn && values.length > 0) {return [@@ -928,6 +1028,13 @@ export function useSidebarFilterState(values,availableValues,}));++ // Re-checking the last excluded value empties the exclusion set:+ // return to the implicit-all default instead of persisting an empty+ // "none of" filter.+ if (finalOperator === "none of" && finalValues.length === 0) {+ return other;+ }}const filterType: "arrayOptions" | "stringOptions" =@@ -1002,12 +1109,15 @@ export function useSidebarFilterState((columnDefinition) => columnDefinition.id === column,)?.type;const existingFilter = filterState.find((f) => f.column === column);+ // "Only" is a positive selection: an active "none of" exclusion is+ // replaced rather than preserved β `none of [value]` would mean+ // everything-EXCEPT-value, the opposite of "only". "all of" is kept+ // (all of one value = has that value).const operator =columnType === "arrayOptions" &&existingFilter?.type === "arrayOptions" &&(existingFilter.operator === "any of" ||- existingFilter.operator === "all of" ||- existingFilter.operator === "none of")+ existingFilter.operator === "all of")? existingFilter.operator: "any of";updateFilter(column, [value], operator);@@ -1843,6 +1953,10 @@ export function useSidebarFilterState(// effective state, so it never surfaces a "Clear" badge).// - Other facets: active when text filters exist or checkbox selections differ from unfiltered.// Special case: "all of" with all values selected is still active.+ // Special case: a "none of" filter renders as its complement, so+ // when every exclusion sits outside the current option list the+ // checkboxes all show checked β the live filter must still surface+ // its "Clear" affordance.const isActive =hasTextFilters ||(isManagedEnvironmentFacet@@ -1850,8 +1964,7 @@ export function useSidebarFilterState(: (currentOperator === "all of" &&(selectedValues.length === availableValues.length ||hasExplicitCheckboxFilterWhileLoading)) ||- (currentOperator === "none of" &&- hasExplicitCheckboxFilterWhileLoading) ||+ (currentOperator === "none of" && hasExplicitCheckboxFilter) ||hasCheckboxSelections ||hasExplicitCheckboxFilterWhileLoading);const disableState = getFacetDisabledState(facet);@@ -1877,10 +1990,11 @@ export function useSidebarFilterState(onChange: (values: string[]) => updateFilter(facet.column, values),onOnlyChange: (value: string) => {if (selectedValues.length === 1 && selectedValues.includes(value)) {- updateFilter(- facet.column,- selectedValues.filter((v) => v !== value),- );+ // The label reads "All" in this state: re-select every option.+ // Passing the full option list (not []) matters for an active+ // "none of" filter β empty values there would re-derive to+ // "exclude everything", the opposite of the label's promise.+ updateFilter(facet.column, availableValues);} else {updateFilterOnly(facet.column, value);}@@ -1900,8 +2014,10 @@ export function useSidebarFilterState();setFilterState(withoutAll);},- // Only add operator toggle for arrayOptions columns- operator: isArrayOptions ? currentOperator : undefined,+ // The operator is exposed for every checkbox facet so the "none of"+ // display logic (pinning excluded rows) works on stringOptions too;+ // the SOME/ALL/NONE toggle itself is gated on onOperatorChange below.+ operator: currentOperator,onOperatorChange: isArrayOptions? (op: "any of" | "all of" | "none of") =>updateOperator(facet.column, op)diff --git a/web/src/features/filters/lib/filter-query-encoding.ts b/web/src/features/filters/lib/filter-query-encoding.tsindex 155812ee82..5e4924021c 100644--- a/web/src/features/filters/lib/filter-query-encoding.ts+++ b/web/src/features/filters/lib/filter-query-encoding.ts@@ -62,6 +62,12 @@ export type GenericFilterOptions = Record<>;// Pure helper: compute UI-selected values from a filter entry and available values+// Checkboxes always show the KEPT set: "no filter" renders every option+// checked, and a `none of [excluded]` filter renders as everything-but-excluded+// checked β for stringOptions and arrayOptions alike (LFE-10717). This makes+// the deselect gesture round-trip: unchecking a value from the implicit-all+// state persists `none of [value]`, which displays as exactly that value+// unchecked.export function computeSelectedValues(availableValues: string[],filterEntry:@@ -70,9 +76,6 @@ export function computeSelectedValues(): string[] {if (!filterEntry) return availableValues;const values = (filterEntry.value as string[]) ?? [];- if (filterEntry.type === "arrayOptions") {- return values;- }if (filterEntry.operator === "none of") {const excluded = new Set(values);return availableValues.filter((v) => !excluded.has(v));@@ -80,6 +83,17 @@ export function computeSelectedValues(return values;}+/**+ * Upper bound for a serialized `?filter=` value that may be written to the+ * URL. Browsers tolerate very long URLs, but the full request head (URL line+ * + cookies + headers) is capped at ~16KB by Node's HTTP server and most+ * proxies β an oversized filter query 431s the refresh/share round-trip it+ * exists for (LFE-10717). States above this budget are kept in the+ * session-storage mirror only: same-tab refreshes keep working, a copied link+ * degrades to "no filter" instead of a dead page.+ */+export const MAX_URL_FILTER_QUERY_LENGTH = 4000;+/*** Encodes FilterState to the legacy semicolon-delimited format* Format: columnId;type;key;operator;valuediff --git a/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsx b/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsxnew file mode 100644index 0000000000..9dd8aa2a1f--- /dev/null+++ b/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsx@@ -0,0 +1,443 @@+/**+ * Gesture-level tests for arrayOptions exclusion semantics (LFE-10717).+ *+ * The sidebar facet renders "no filter" as every option checked. Unchecking a+ * value from that implicit-all state means "exclude this value", which for a+ * multi-valued column (a session can have several userIds, a trace several+ * tags) is only expressible as `none of [value]` β NOT `any of [all others]`,+ * which both returns wrong results (rows carrying the excluded value alongside+ * another one still match) and materializes O(option-count) state into the URL+ * (HTTP 431 at ~1000 user IDs).+ *+ * Display follows the unified checked=kept model: a `none of [x]` filter+ * renders as everything-but-x checked with the NONE operator active, exactly+ * like stringOptions none-of filters always have.+ */++import { fireEvent, render, screen } from "@testing-library/react";+import {+ useSidebarFilterState,+ type CategoricalUIFilter,+} from "./hooks/useSidebarFilterState";+import type { FilterConfig } from "./lib/filter-config";++// The hook calls useQueryParam unconditionally even for the "memory" state+// location used here; stub it out so no QueryParamProvider is needed.+vi.mock("use-query-params", async () => {+ const actual = await vi.importActual("use-query-params");+ return {+ ...actual,+ StringParam: {},+ useQueryParam: () => [null, () => {}] as const,+ };+});++const TAGS_FILTER_CONFIG: FilterConfig = {+ tableName: "traces",+ columnDefinitions: [+ {+ id: "tags",+ name: "Tags",+ type: "arrayOptions",+ options: [],+ internal: 't."tags"',+ },+ ],+ facets: [+ {+ type: "categorical",+ column: "tags",+ label: "Tags",+ },+ ],+};++const TAG_OPTIONS = {+ tags: ["tag-1", "tag-2", "tag-3", "tag-4"],+};++function ExclusionHarness() {+ const queryFilter = useSidebarFilterState(TAGS_FILTER_CONFIG, TAG_OPTIONS, {+ stateLocation: "memory",+ });++ const facet = queryFilter.filters.find(+ (f): f is CategoricalUIFilter => f.column === "tags",+ );+ if (!facet) throw new Error("tags facet missing");++ // Mirrors the checkbox handler in data-table-controls.tsx: checking adds the+ // option to the current value list, unchecking removes it.+ const toggle = (option: string) => {+ const next = facet.value.includes(option)+ ? facet.value.filter((v) => v !== option)+ : [...facet.value, option];+ facet.onChange(next);+ };++ return (+ <div>+ <pre data-testid="filter-state">+ {JSON.stringify(queryFilter.filterState)}+ </pre>+ <pre data-testid="facet-value">{JSON.stringify(facet.value)}</pre>+ <pre data-testid="facet-operator">{facet.operator ?? "undefined"}</pre>+ <pre data-testid="facet-active">{String(facet.isActive)}</pre>+ {TAG_OPTIONS.tags.map((option) => (+ <button+ key={option}+ data-testid={`toggle-${option}`}+ onClick={() => toggle(option)}+ >+ toggle {option}+ </button>+ ))}+ <button+ data-testid="only-tag-3"+ onClick={() => facet.onOnlyChange?.("tag-3")}+ >+ only tag-3+ </button>+ <button+ data-testid="only-tag-4"+ onClick={() => facet.onOnlyChange?.("tag-4")}+ >+ only tag-4+ </button>+ <button+ data-testid="operator-any-of"+ onClick={() => facet.onOperatorChange?.("any of")}+ >+ SOME+ </button>+ <button+ data-testid="operator-none-of"+ onClick={() => facet.onOperatorChange?.("none of")}+ >+ NONE+ </button>+ <button+ data-testid="set-stale-exclusion"+ onClick={() =>+ queryFilter.setFilterState([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["stale-tag"],+ },+ ])+ }+ >+ set stale exclusion+ </button>+ </div>+ );+}++const NAME_FILTER_CONFIG: FilterConfig = {+ tableName: "traces",+ columnDefinitions: [+ {+ id: "name",+ name: "Name",+ type: "stringOptions",+ options: [],+ internal: 't."name"',+ },+ ],+ facets: [+ {+ type: "categorical",+ column: "name",+ label: "Name",+ },+ ],+};++const NAME_OPTIONS = {+ name: ["checkout", "search", "chat"],+};++// stringOptions facets share the display pipeline: the operator must be+// exposed there too so the none-of pinning in data-table-controls can surface+// the just-unchecked row (the SOME/ALL/NONE toggle stays arrayOptions-only via+// onOperatorChange).+function StringOptionsHarness() {+ const queryFilter = useSidebarFilterState(NAME_FILTER_CONFIG, NAME_OPTIONS, {+ stateLocation: "memory",+ });++ const facet = queryFilter.filters.find(+ (f): f is CategoricalUIFilter => f.column === "name",+ );+ if (!facet) throw new Error("name facet missing");++ return (+ <div>+ <pre data-testid="filter-state">+ {JSON.stringify(queryFilter.filterState)}+ </pre>+ <pre data-testid="facet-operator">{facet.operator ?? "undefined"}</pre>+ <pre data-testid="facet-has-toggle">+ {String(facet.onOperatorChange !== undefined)}+ </pre>+ <button+ data-testid="uncheck-search"+ onClick={() =>+ facet.onChange(facet.value.filter((v) => v !== "search"))+ }+ >+ uncheck search+ </button>+ <button+ data-testid="check-search"+ onClick={() => facet.onChange([...facet.value, "search"])}+ >+ check search+ </button>+ <button+ data-testid="set-stale-name-exclusion"+ onClick={() =>+ queryFilter.setFilterState([+ {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["stale-name"],+ },+ ])+ }+ >+ set stale name exclusion+ </button>+ </div>+ );+}++const getFilterState = () =>+ JSON.parse(screen.getByTestId("filter-state").textContent ?? "[]");+const getFacetValue = () =>+ JSON.parse(screen.getByTestId("facet-value").textContent ?? "[]");+const getFacetOperator = () => screen.getByTestId("facet-operator").textContent;+const getFacetActive = () =>+ screen.getByTestId("facet-active").textContent === "true";++describe("arrayOptions facet exclusion gestures (LFE-10717)", () => {+ it("unchecking one value from implicit-all produces a compact none-of filter and inverted display", () => {+ render(<ExclusionHarness />);++ // Implicit-all default: everything checked, no persisted filter.+ expect(getFacetValue()).toEqual(TAG_OPTIONS.tags);+ expect(getFilterState()).toEqual([]);++ fireEvent.click(screen.getByTestId("toggle-tag-2"));++ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-2"],+ },+ ]);+ // Display round-trips: the unchecked value stays unchecked, the rest stay+ // checked, and the NONE operator is active.+ expect(getFacetValue()).toEqual(["tag-1", "tag-3", "tag-4"]);+ expect(getFacetOperator()).toBe("none of");+ expect(getFacetActive()).toBe(true);+ });++ it("accumulates exclusions, drops re-checked ones, and clears the filter when the last exclusion is re-checked", () => {+ render(<ExclusionHarness />);++ fireEvent.click(screen.getByTestId("toggle-tag-2"));+ fireEvent.click(screen.getByTestId("toggle-tag-3"));+ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-2", "tag-3"],+ },+ ]);++ // Re-check tag-2: only tag-3 stays excluded.+ fireEvent.click(screen.getByTestId("toggle-tag-2"));+ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-3"],+ },+ ]);++ // Re-check the last exclusion: back to the implicit-all default, no+ // lingering empty none-of filter.+ fireEvent.click(screen.getByTestId("toggle-tag-3"));+ expect(getFilterState()).toEqual([]);+ expect(getFacetValue()).toEqual(TAG_OPTIONS.tags);+ expect(getFacetActive()).toBe(false);+ });++ it('label-click "Only" during an active exclusion selects exactly that value (any of)', () => {+ render(<ExclusionHarness />);++ fireEvent.click(screen.getByTestId("toggle-tag-2"));+ fireEvent.click(screen.getByTestId("only-tag-3"));++ // "Only" always means only: the exclusion is dropped in favor of a+ // positive single-value selection, not `none of [tag-3]` (which would be+ // the opposite of "only").+ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "any of",+ value: ["tag-3"],+ },+ ]);+ expect(getFacetValue()).toEqual(["tag-3"]);+ expect(getFacetOperator()).toBe("any of");+ });++ it("SOMEβNONE operator toggle carries the value list (semantic inversion)", () => {+ render(<ExclusionHarness />);++ fireEvent.click(screen.getByTestId("toggle-tag-2"));+ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-2"],+ },+ ]);++ // NONE β SOME: "exclude tag-2" becomes "match tag-2".+ fireEvent.click(screen.getByTestId("operator-any-of"));+ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "any of",+ value: ["tag-2"],+ },+ ]);+ expect(getFacetValue()).toEqual(["tag-2"]);++ // SOME β NONE: and back.+ fireEvent.click(screen.getByTestId("operator-none-of"));+ expect(getFilterState()).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["tag-2"],+ },+ ]);+ expect(getFacetValue()).toEqual(["tag-1", "tag-3", "tag-4"]);+ });++ it('label-click "All" on the last kept value resets the facet instead of excluding everything', () => {+ // With only one value left checked the label affordance reads "All"+ // (re-select everything). Under an active none-of filter this must clear+ // the filter β deriving exclusions from an empty checked set would yield+ // `none of [every option]`, the exact opposite of the label.+ render(<ExclusionHarness />);++ fireEvent.click(screen.getByTestId("toggle-tag-1"));+ fireEvent.click(screen.getByTestId("toggle-tag-2"));+ fireEvent.click(screen.getByTestId("toggle-tag-3"));+ expect(getFacetValue()).toEqual(["tag-4"]);++ // onOnlyChange on the single remaining checked value = the "All" branch.+ fireEvent.click(screen.getByTestId("only-tag-4"));++ expect(getFilterState()).toEqual([]);+ expect(getFacetValue()).toEqual(TAG_OPTIONS.tags);+ expect(getFacetActive()).toBe(false);+ });++ it("toggling NONE without any selection is a no-op (no vacuous none-of filter persisted)", () => {+ render(<ExclusionHarness />);++ fireEvent.click(screen.getByTestId("operator-none-of"));++ expect(getFilterState()).toEqual([]);+ expect(getFacetValue()).toEqual(TAG_OPTIONS.tags);+ expect(getFacetActive()).toBe(false);+ });++ it("keeps the facet active for an exclusion outside the current option list", () => {+ // The excluded value fell out of the (top-N-capped / time-scoped) option+ // list: every visible checkbox is checked, but the filter is still live β+ // the facet must surface that (Clear affordance) instead of looking idle.+ render(<ExclusionHarness />);++ fireEvent.click(screen.getByTestId("set-stale-exclusion"));++ expect(getFacetValue()).toEqual(TAG_OPTIONS.tags);+ expect(getFacetOperator()).toBe("none of");+ expect(getFacetActive()).toBe(true);+ });+});++describe("stringOptions facet operator plumbing (LFE-10717)", () => {+ it("exposes the none-of operator (for exclusion pinning) without an operator toggle", () => {+ render(<StringOptionsHarness />);++ fireEvent.click(screen.getByTestId("uncheck-search"));++ expect(getFilterState()).toEqual([+ {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["search"],+ },+ ]);+ expect(screen.getByTestId("facet-operator").textContent).toBe("none of");+ expect(screen.getByTestId("facet-has-toggle").textContent).toBe("false");+ });++ it("carries an out-of-list exclusion across checkbox interactions (parity with arrayOptions)", () => {+ render(<StringOptionsHarness />);++ fireEvent.click(screen.getByTestId("set-stale-name-exclusion"));+ // Every visible box is checked (the stale value is not listed); unchecking+ // another value must extend the exclusion set, not silently drop the+ // stale one.+ fireEvent.click(screen.getByTestId("uncheck-search"));++ expect(getFilterState()).toEqual([+ {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["stale-name", "search"],+ },+ ]);++ // Re-checking search keeps only the stale exclusion alive.+ fireEvent.click(screen.getByTestId("check-search"));+ expect(getFilterState()).toEqual([+ {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["stale-name"],+ },+ ]);+ });++ it("re-checking the last excluded value still clears a stringOptions none-of filter", () => {+ render(<StringOptionsHarness />);++ fireEvent.click(screen.getByTestId("uncheck-search"));+ fireEvent.click(screen.getByTestId("check-search"));++ expect(getFilterState()).toEqual([]);+ });+});diff --git a/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsx b/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsxindex 1335669a2f..8d519badc5 100644--- a/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsx+++ b/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsx@@ -114,6 +114,19 @@ const FILTER_B: FilterState = [},];+// Encodes to well over MAX_URL_FILTER_QUERY_LENGTH characters (LFE-10717).+const OVERSIZED_FILTER: FilterState = [+ {+ column: "name",+ type: "stringOptions",+ operator: "any of",+ value: Array.from(+ { length: 400 },+ (_, i) => `checkout-step-${i}-abcdefghijklmnop`,+ ),+ },+];+function SessionPersistenceHarness(props: { contextId?: string | null }) {const queryFilter = useSidebarFilterState(TEST_FILTER_CONFIG, TEST_OPTIONS, {stateLocation: "urlAndSessionStorage",@@ -137,6 +150,12 @@ function SessionPersistenceHarness(props: { contextId?: string | null }) {>Clear</button>+ <button+ data-testid="set-oversized"+ onClick={() => queryFilter.setFilterState(OVERSIZED_FILTER)}+ >+ Set oversized+ </button></div>);}@@ -390,3 +409,91 @@ describe("useSidebarFilterState session persistence", () => {});});});++describe("oversized filter queries stay out of the URL (LFE-10717)", () => {+ // An oversized serialized filter state must never reach the URL: the full+ // request head (URL + cookies + headers) is capped at ~16KB by Node and+ // most proxies, so a giant `?filter=` 431s on the refresh round-trip. The+ // state falls back to the session-storage mirror instead β same-tab+ // refreshes keep working; a copied link degrades to "no filter" rather+ // than a dead page.+ const encodedOversized = encodeFiltersGeneric(OVERSIZED_FILTER);+ const encodedFilterB = encodeFiltersGeneric(FILTER_B);+ const sessionKey = buildSidebarFilterQueryStorageKey({+ tableName: TEST_FILTER_CONFIG.tableName,+ contextId: null,+ });+ const encodeStoredState = (query: string) =>+ JSON.stringify({ contextId: null, query });++ beforeEach(() => {+ sessionStorage.clear();+ queryParamStore.clear();+ deferredQueryParams.clear();+ });++ const getExplicitState = () =>+ JSON.parse(screen.getByTestId("explicit-state").textContent ?? "[]");++ it("applies the filter, persists it to session storage, and keeps the URL param absent", async () => {+ render(<SessionPersistenceHarness />);++ fireEvent.click(screen.getByTestId("set-oversized"));++ // State applies in the same interaction.+ expect(getExplicitState()).toEqual(OVERSIZED_FILTER);++ await waitFor(() => {+ expect(sessionStorage.getItem(sessionKey)).toBe(+ encodeStoredState(encodedOversized),+ );+ });+ // Give the async query-param writer a chance to (incorrectly) flush.+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(queryParamStore.has("filter")).toBe(false);+ expect(getExplicitState()).toEqual(OVERSIZED_FILTER);+ });++ it("restores the oversized filter from session storage on remount (same-tab refresh)", async () => {+ sessionStorage.setItem(sessionKey, encodeStoredState(encodedOversized));++ render(<SessionPersistenceHarness />);++ await waitFor(() => {+ expect(getExplicitState()).toEqual(OVERSIZED_FILTER);+ });+ // The sanitize/mirror effects must not push the oversized query into the URL.+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(queryParamStore.has("filter")).toBe(false);+ });++ it("replaces an existing URL filter and resumes URL writes once the state fits again", async () => {+ queryParamStore.set("filter", encodedFilterB);++ render(<SessionPersistenceHarness />);++ await waitFor(() => {+ expect(getExplicitState()).toEqual(FILTER_B);+ });++ // Oversized write removes the stale URL param instead of replacing it.+ fireEvent.click(screen.getByTestId("set-oversized"));+ expect(getExplicitState()).toEqual(OVERSIZED_FILTER);+ await waitFor(() => {+ expect(queryParamStore.has("filter")).toBe(false);+ });++ // A later, small state goes back to normal URL persistence β the+ // optimistic pending query must not get stuck on the oversized value.+ fireEvent.click(screen.getByTestId("set-filter-b"));+ await waitFor(() => {+ expect(queryParamStore.get("filter")).toBe(encodedFilterB);+ });+ expect(getExplicitState()).toEqual(FILTER_B);+ await waitFor(() => {+ expect(sessionStorage.getItem(sessionKey)).toBe(+ encodeStoredState(encodedFilterB),+ );+ });+ });+});