EnxDev commented on code in PR #44739: URL: https://github.com/apache/superset/pull/44739#discussion_r4142126347
########## superset-frontend/src/components/FilterableTable/sortResults.ts: ########## @@ -0,0 +1,156 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +type CellValue = string | number | null; + +// Every pattern below is a single flat run of digits, so matching stays linear +// in the input length; the optional parts are split off by hand instead of +// nesting quantified groups, which could backtrack catastrophically. +const DIGITS = /^\d*$/; +const EXPONENT = /^[+-]?\d+$/; + +/** Split `text` at its first `e`/`E`; `null` when the exponent is malformed. */ +function splitExponent(text: string): [string, string | undefined] | null { + const at = text.search(/[eE]/); + if (at === -1) return [text, undefined]; + const exponent = text.slice(at + 1); + return EXPONENT.test(exponent) ? [text.slice(0, at), exponent] : null; +} + +// Compare significands and decimal orders, never coerce exact strings to Number. +// Keeping the exponent separate also avoids allocating 10**exponent zeroes. +export function decimalParts(value: Exclude<CellValue, null>) { + const text = String(value); + const signed = text[0] === '+' || text[0] === '-'; + const parts = splitExponent(signed ? text.slice(1) : text); + if (!parts) return null; + const [mantissa, exponent] = parts; + const dot = mantissa.indexOf('.'); + const integer = dot === -1 ? mantissa : mantissa.slice(0, dot); + const fraction = dot === -1 ? '' : mantissa.slice(dot + 1); + if ( + !(integer || fraction) || + !DIGITS.test(integer) || + !DIGITS.test(fraction) + ) { + return null; + } + const digits = `${integer}${fraction}`.replace(/^0+/, ''); + return { + sign: digits ? (text[0] === '-' ? -1 : 1) : 0, + digits, + order: + BigInt(digits.length) + BigInt(exponent ?? '0') - BigInt(fraction.length), + }; +} + +// Values sort by type first, so mixed columns stay transitive: numbers (exact +// decimal strings and infinities included) before text, and NaN after both. +const NUMERIC_RANK = 0; +const TEXT_RANK = 1; +const NAN_RANK = 2; + +type SortKey = + | { + rank: typeof NUMERIC_RANK; + // -1 or 1 for an infinity, 0 for a finite value. + infinity: number; + sign: number; + digits: string; + order: bigint; + } + | { rank: typeof TEXT_RANK; text: string } + | { rank: typeof NAN_RANK }; + +function toSortKey(value: Exclude<CellValue, null>): SortKey { + if (typeof value === 'number' ? Number.isNaN(value) : value === 'NaN') { + return { rank: NAN_RANK }; + } + if (value === Infinity || value === 'Infinity') { + return { + rank: NUMERIC_RANK, + infinity: 1, + sign: 1, + digits: '', + order: BigInt(0), + }; + } + if (value === -Infinity || value === '-Infinity') { + return { + rank: NUMERIC_RANK, + infinity: -1, + sign: -1, + digits: '', + order: BigInt(0), + }; + } + const parts = decimalParts(value); + return parts + ? { rank: NUMERIC_RANK, infinity: 0, ...parts } + : { rank: TEXT_RANK, text: String(value) }; +} + +// Parsing dominates the cost of sorting decimal strings, and a sort compares +// each cell O(log n) times, so keys are cached per value. The cache is cleared +// whenever it outgrows a large result set to keep memory bounded. +const SORT_KEY_CACHE_LIMIT = 250_000; +const sortKeyCache = new Map<Exclude<CellValue, null>, SortKey>(); Review Comment: This cache is module-scoped, so after a sort it holds up to 250k cell values for the life of the page, long after the user has run another query or closed the tab. Sort a column of large JSON or text cells and it keeps that memory pinned even though redux has already dropped the result set. Could it be per table instead? A Map held in a ref inside `FilterableTable`, cleared when `data` changes and on unmount, would go away along with the results and keep the speedup. ########## superset/result_set.py: ########## @@ -88,6 +89,11 @@ def stringify_values(array: NDArray[Any]) -> NDArray[Any]: # Non-JSON-serializable value (e.g. bytes, custom # objects): fall back to str() to avoid crashing. obj[...] = str(val) + elif isinstance(val, Decimal): + # str() switches to scientific notation for small or + # large exponents (-1.0E-7), which CSV export would + # formula-escape. NaN and Infinity have no exact value. + obj[...] = format(val, "f") if val.is_finite() else None Review Comment: This also runs for chart and dataset queries, not just SQL Lab. `Database.get_df` goes through `load_into_dataframe` into `SupersetResultSet` (`superset/models/core.py:1076`). So a chart on a Postgres `numeric` column holding `NaN` or `Infinity` gets null where it used to get the string `"NaN"`, and Decimals mixed with floats come out in fixed point instead of `-1.0E-7`. Seems like the right behavior to me, but the UPDATING entry says chart result serialization is unchanged. Worth a sentence there covering this case. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
