From 2524895492a4d1620e9b6cd5b96118e5165abb5d Mon Sep 17 00:00:00 2001 From: broisnees Date: Tue, 24 Nov 2026 17:13:26 +0000 Subject: [PATCH] Load tables with wide values and slow links much faster Wide columns are decided on pg_column_size alone (header only) and ship as their stored size past 4KB. The old middle branch ran octet_length(col::text) and left(col::text, 512), each a full detoast and jsonb-to-text conversion: on a 454KB-a-row resume table, 343 rows spent 14s in one and 14s in the other against 3ms for pg_column_size, and a full load of 1,762 rows went from 11.8s of server time to 0.6s. Window target 2MB to 600KB, heavy-view bar 8MB to 1.5MB, first probe 200 to 100 rows. Rows on screen that their in-flight window does not cover yet are fetched alone (fillVisibleGap), and views under 10,000 rows fill their remaining windows in the background. A first open reads the table's primary key from the schema's column structure, so the probe is in window order and becomes window 0 instead of being fetched twice; without it the probe only measures, at 20 rows. A fresh view resets the stale visible range that made window 0 refetch the screenful the probe had just painted. Measured against a remote Postgres through a 40ms-each-way, 10 Mbit proxy: first rows of a 208k-row table in 0.44s, and the resume table streams 100-row windows in under a second each. --- .changeset/faster-table-loads.md | 5 + src-tauri/src/db/wide_columns.rs | 69 ++++++-------- src/lib/components/StudioShell.svelte | 130 +++++++++++++++++++++++++- src/lib/row-window.js | 34 +++++-- src/lib/row-window.test.js | 13 ++- 5 files changed, 196 insertions(+), 55 deletions(-) create mode 100644 .changeset/faster-table-loads.md diff --git a/.changeset/faster-table-loads.md b/.changeset/faster-table-loads.md new file mode 100644 index 00000000..a3570f94 --- /dev/null +++ b/.changeset/faster-table-loads.md @@ -0,0 +1,5 @@ +### Fixes +- **Tables with large JSON or text columns open in a fraction of the time** - A big value is now sent as its size, decided from Postgres's stored size without reading the value, and loads when you open the cell. Before, each medium-sized value was decompressed and converted to text twice just to cut a short preview: a 1,762-row resume table took 12.6 s to load, and now takes under a second on the server. +- **Rows on screen come first** - Windows of rows are about 600 KB instead of 2 MB, and rows you scroll to while their window is still downloading are fetched on their own, so a slow link no longer leaves the grid on skeletons for seconds. +- **Medium tables stream in full** - A table of a few thousand wide rows streams in windows instead of one large response, and a table under 10,000 rows keeps loading the rest in the background until every row is in. +- **No double fetch on first open** - The first page of a table now comes back in the order the rest of the table loads in, so it is kept instead of fetched again. When that order is not known yet, the first fetch is a 20-row measure instead of a full screen. diff --git a/src-tauri/src/db/wide_columns.rs b/src-tauri/src/db/wide_columns.rs index 9fb3dce1..5fa1e3c3 100644 --- a/src-tauri/src/db/wide_columns.rs +++ b/src-tauri/src/db/wide_columns.rs @@ -11,7 +11,7 @@ //! `WIDE_COLUMN_AVG_BYTES` are selected as a stand-in instead of a value: //! //! ```sql -//! CASE WHEN pg_column_size("resume") > 262144 +//! CASE WHEN pg_column_size("resume") > 4096 //! THEN jsonb_build_object('__strokeOversize', true, 'dataType', 'jsonb', 'bytes', pg_column_size("resume")) //! ELSE jsonb_build_object('__strokeInline', to_jsonb("resume")) //! END AS "resume" @@ -51,8 +51,6 @@ use std::time::{Duration, Instant}; use serde_json::Value; -use super::sql_util::CELL_VALUE_CAP; - /// Average bytes per value past which a column is fetched as a preview. /// /// 32KB is the point where one column outweighs a whole page of ordinary ones: @@ -76,30 +74,22 @@ const SAMPLE_ROWS: i64 = 500; /// the sample is skipped entirely - which is the path almost every table takes. const TOAST_SAMPLE_FLOOR: i64 = 1024 * 1024; -/// Stored size above which a row's TEXT length is checked as well. -/// -/// `pg_column_size` is the COMPRESSED size, and these payloads compress -/// extraordinarily well - a jsonb holding a file as an array of byte integers -/// ran 8.4MB stored against 18.1MB of text, and rows well under the cap on disk -/// were shipping multiple megabytes each. The text check materialises the value, -/// so it is worth about 260ms a page on the table it was measured against, and -/// it is what makes the page size bounded rather than hopeful. Below the floor -/// no amount of compression can reach the cap, so those rows skip it. -const TEXT_CHECK_FLOOR: usize = 1024; - -/// Text size past which a wide column's value ships as a preview in a page. +/// Stored size up to which a wide column's value ships whole in a page. /// -/// The grid draws about forty characters of a cell, yet everything under the -/// 256KB cap used to ship whole: a 50-row page of a resume table moved 823KB -/// of one jsonb column (1.1MB in all), and over a slower link a few of those -/// in flight left the grid on skeletons. Past 8KB the value arrives as its -/// size and its first `PREVIEW_CHARS`; that page is 50KB of the column (341KB -/// in all), and the value loads when the cell is opened or edited. -const GRID_INLINE_BYTES: usize = 8 * 1024; - -/// How much of a previewed value ships: enough for the grid, a tooltip and -/// the first lines of the JSON view. -const PREVIEW_CHARS: usize = 512; +/// Decided on `pg_column_size` alone, which reads the varlena header and never +/// touches the value. Earlier cuts also measured `octet_length(col::text)` and +/// cut a 512-character `left(col::text, 512)` preview for values between 1KB +/// and the 256KB cap, and that was the slow part: both casts detoast, +/// decompress and re-serialise the whole value. On a resume table averaging +/// 454KB stored (about 1MB of JSON text), 343 rows spent 14.2s in the +/// `octet_length` alone and 13.7s more in `left`, against 3ms for +/// `pg_column_size`; opening that table took 12.6s, and loading all 1,762 rows +/// took most of the server's time. Values past this size now arrive as their +/// stored size, which costs nothing, and load whole when the cell is opened +/// (`fetch_cell_value`), as values past the cap always did. 4KB stored is +/// under Postgres's own TOAST threshold neighbourhood, so what ships inline is +/// a small value, not a compressed big one. +const GRID_INLINE_STORED_BYTES: usize = 4 * 1024; #[derive(Clone, Debug)] pub struct WideColumn { @@ -409,18 +399,14 @@ pub fn projection(all_columns: &[String], wide: &[WideColumn]) -> Option .find(|w| &w.name == name) .map(|w| w.type_name.replace('\'', "''")) .unwrap_or_default(); + // One branch on the header-only stored size: nothing here reads + // a large value. See GRID_INLINE_STORED_BYTES. format!( - "CASE WHEN pg_column_size({quoted}) > {cap} \ + "CASE WHEN pg_column_size({quoted}) > {inline} \ THEN jsonb_build_object('__strokeOversize', true, 'dataType', '{col_type}', \ 'bytes', pg_column_size({quoted})) \ - WHEN pg_column_size({quoted}) > {floor} AND octet_length({quoted}::text) > {inline} \ - THEN jsonb_build_object('__strokeOversize', true, 'dataType', '{col_type}', \ - 'bytes', octet_length({quoted}::text), 'preview', left({quoted}::text, {preview})) \ ELSE jsonb_build_object('__strokeInline', to_jsonb({quoted})) END AS {quoted}", - cap = CELL_VALUE_CAP, - floor = TEXT_CHECK_FLOOR, - inline = GRID_INLINE_BYTES, - preview = PREVIEW_CHARS, + inline = GRID_INLINE_STORED_BYTES, ) } else { quoted @@ -484,15 +470,12 @@ mod tests { assert!(sql.starts_with("\"id\", CASE WHEN pg_column_size(\"resume\")")); assert!(sql.contains("'__strokeOversize', true")); assert!(sql.contains("'dataType', 'jsonb'")); - // No preview past the cap: building one would detoast every over-cap - // value on the page. Under it the value is read for its length anyway, - // so that branch carries the first 512 characters. - let (over_cap, under_cap) = sql.split_once("WHEN pg_column_size(\"resume\") > 1024").expect("two branches"); - assert!(!over_cap.contains("left(")); - assert!(under_cap.contains("'preview', left(\"resume\"::text, 512)")); - assert!(under_cap.contains("octet_length(\"resume\"::text) > 8192")); - // The compressed size is the cheap gate; the text length is the honest one. - assert!(sql.contains("length(\"resume\"::text) >")); + // One branch, on the stored size only: no cast reads the value, so + // nothing in a page detoasts a wide value. + assert!(sql.contains("pg_column_size(\"resume\") > 4096")); + assert!(!sql.contains("::text")); + assert!(!sql.contains("left(")); + assert!(!sql.contains("octet_length")); assert!(sql.contains("AS \"resume\"")); assert!(sql.ends_with(", \"status\"")); // Every column is still selected, in order. diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 2109461b..eff9ca04 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -2813,6 +2813,33 @@ let rowSearch = $state('') let _schemaColumnsGen = 0 /** @type {Promise} */ let _schemaColumnsReady = Promise.resolve() + /** + * Each table's primary key, from the same call. A first open does not know + * its table's key until the rows come back, so the first page went out in + * no order, could not be reused as window 0 (windows slice the key's + * order), and was fetched again: on a wide table, the first 1.3 MB twice. + * Plain, not reactive: only read when a load starts. + * @type {Record} + */ + let _schemaPks = {} + /** A table's primary key when this schema's columns are loaded, else null. @param {string} schema @param {string | null} table */ + function knownPrimaryKey(schema, table) { + if (!table || `${persistConnectionId}:${schema}` !== _schemaColumnsFor) return null + return _schemaPks[table] ?? null + } + // Loaded with the table list rather than on first completion: the keys it + // carries are what lets a first open's page count as its first window. + // Once per connection and schema: the table list changes as its counts fill + // in, and re-reading the whole schema's columns each time cost a 0.5-1.2 s + // catalog query per change on a large remote schema. Completion still + // refreshes it on a new table (loadSchemaColumns' own key). + $effect(() => { + void _tableNames + if (!connection || !activeSchema) return + untrack(() => { + if (`${persistConnectionId}:${activeSchema}` !== _schemaColumnsFor) void loadSchemaColumns() + }) + }) $effect(() => { void _tableNames _schemaColumnsGen++ @@ -2830,16 +2857,22 @@ let rowSearch = $state('') if (owner !== _schemaColumnsFor) { _schemaColumnsFor = owner _schemaColumns = {} + _schemaPks = {} } _schemaColumnsReady = getSchemaColumnStructure(activeSchema) .then((rows) => { if (_schemaColumnsKey !== key) return /** @type {Record>} */ const next = {} + /** @type {Record} */ + const pks = {} for (const { table, columns: cols } of rows ?? []) { next[table] = cols.map((c) => ({ name: c.name, type: c.dataType ?? '' })) + const pk = cols.filter((c) => c.isPrimaryKey).map((c) => c.name) + if (pk.length) pks[table] = pk } _schemaColumns = next + _schemaPks = pks }) .catch(() => { // Let the next request try again rather than caching the failure. @@ -7509,6 +7542,7 @@ let rowSearch = $state('') // tenth of a second. Worth it whenever the window is heavy or the link slow. const heavyWindow = limit * (_windowBytesPerRow || 0) > SCREENFUL_FIRST_BYTES || _windowSlow if (!local && (limit > VIEWPORT_FIRST_MIN || heavyWindow) && _visStart >= start && _visStart < start + limit && rows[_visStart] === undefined) { + _screenfulInFlight++ const from = Math.max(start, _visStart - 20) const count = Math.min(start + limit, Math.max(_visEnd, _visStart) + 60) - from try { @@ -7519,6 +7553,11 @@ let rowSearch = $state('') dataVersion++ tracePoint(`window ${start} screenful ${got.length} rows ${Math.round(performance.now() - t0)}ms`) } catch { /* the full window below still runs */ } + finally { + _screenfulInFlight = Math.max(0, _screenfulInFlight - 1) + // Scrolled while it was out: whatever is still missing on screen. + if (seq === _windowSeq) fillVisibleGap(_visStart, _visEnd) + } } const data = local ? { rows: local } : await getTableRows(activeSchema, activeTable, limit, _windowBase + start, { ...currentRowQuery(false), keyset, fetchTag: windowFetchTag() }) // Rolling, so the measure tracks the connection rather than latching on the @@ -7586,6 +7625,25 @@ let rowSearch = $state('') const w = _windowQueue.splice(i, 1)[0] void fetchWindow(w) } + fillRemainingWindows() + } + + /** + * A view small enough to hold whole streams the rest in once the screen is + * served: one window at a time, only while nothing the user asked for is + * queued or in flight. A 4,000-row table used to be either one request + * (seconds of nothing past the first 200 rows on a home link) or, windowed, + * only the windows a scroll had reached. Larger views have the mirror for + * this (startMirror), so they keep loading on demand. + */ + function fillRemainingWindows() { + if (!windowed || _windowInFlight > 0 || _windowQueue.length > 0) return + if (_windowCount >= MIRROR_MIN_ROWS || _windowBase !== 0) return + for (let w = 0; w * _windowRows < _windowCount; w++) { + if (_windowLoaded.has(w) || _windowFetching.has(w) || _windowFailed.has(w)) continue + void fetchWindow(w) + return + } } /** @@ -7689,6 +7747,7 @@ let rowSearch = $state('') (w) => w >= 0 && w * _windowRows < _windowCount && !_windowLoaded.has(w) && !_windowFetching.has(w), ) pumpWindowQueue() + fillVisibleGap(start, end) if (_visRangeTimer) clearTimeout(_visRangeTimer) _visRangeTimer = setTimeout(() => { _visRangeTimer = null @@ -7696,6 +7755,56 @@ let rowSearch = $state('') }, 300) } + /** + * Rows on screen that no fetch will paint soon: their window is already on + * its way, but it started for another part of the screen (the screenful + * fetched first on open covers the first ~80 rows; scroll to row 60 and + * rows 80-90 waited for the whole window, ~600 KB to 2 MB, seconds over a + * home link, on skeletons). Ask for exactly those rows, alone, the way a + * jump does. Same load generation, so it never cancels the window it is + * racing; whichever lands first fills the gap and the other skips filled + * rows. One at a time, re-checked when it lands. + */ + let _gapInFlight = false + /** Screenful-first fetches running (fetchWindow): they already cover the screen. */ + let _screenfulInFlight = 0 + /** @param {number} start @param {number} end */ + function fillVisibleGap(start, end) { + if (_gapInFlight || _screenfulInFlight > 0 || !windowed || !activeTable) return + const last = Math.min(end, _windowCount - 1) + let from = -1 + for (let i = Math.max(0, start); i <= last; i++) if (rows[i] === undefined) { from = i; break } + if (from < 0) return + let to = from + for (let i = last; i > from; i--) if (rows[i] === undefined) { to = i; break } + // Only behind a window already in flight: a window still queued fetches + // its own screenful first (fetchWindow), and a mirror read is local. + const w = Math.floor(from / _windowRows) + if (!_windowFetching.has(w) || activeMirror()) return + const begin = Math.max(0, from - 10) + const count = Math.min(400, to - begin + 1 + 30, _windowCount - begin) + const seq = _windowSeq + const schema = activeSchema + const table = activeTable + _gapInFlight = true + const t0 = performance.now() + getTableRows(schema, table, count, _windowBase + begin, { ...currentRowQuery(false), fetchTag: windowFetchTag() }) + .then((head) => { + if (seq !== _windowSeq) return + const got = head.rows ?? [] + let filled = 0 + for (let i = 0; i < got.length; i++) if (rows[begin + i] === undefined) { rows[begin + i] = got[i]; filled++ } + if (filled) dataVersion++ + tracePoint(`window gap ${begin}+${got.length} rows ${Math.round(performance.now() - t0)}ms`) + }) + .catch(() => { /* the window still lands */ }) + .finally(() => { + _gapInFlight = false + // Scrolled on while it was out: fill what is on screen now. + if (seq === _windowSeq) fillVisibleGap(_visStart, _visEnd) + }) + } + /** Fetch the full ordered result set in chunks (windowed export/copy path). * Chunked coarser than the scroll windows - nothing is being rendered meanwhile, * so throughput matters more than latency - but still by BYTES, since 50k rows @@ -7802,7 +7911,15 @@ let rowSearch = $state('') // ordered by the primary key too, whenever we already know it. On the very // first load of a table the key arrives with this response, so the probe // can't be ordered yet; its rows are then treated as provisional below. - const probeOrder = wantsWindow ? stableWindowOrder(rowSort, rowSortMore, primaryKey) : null + // On a first open the key comes from the schema's catalog (see + // knownPrimaryKey), so even the first page is in window order. + const orderPk = includeMeta ? (knownPrimaryKey(ownerSchema, ownerTable) ?? primaryKey) : primaryKey + const probeOrder = wantsWindow ? stableWindowOrder(rowSort, rowSortMore, orderPk) : null + // Without that order the probe cannot become window 0: its rows are + // dropped and the window fetched again in order. Then it only measures + // (row weight, columns, count), and 20 rows do that, instead of sending a + // first screenful twice (0.9 MB of it on a wide table, at app start). + const probeSize = probeOrder ? WINDOW_PROBE : 20 // Query shape frozen at call time. The remainder fetch below must not read // it back off the globals - by then they may describe another tab. const ownerQuery = { @@ -7817,7 +7934,7 @@ let rowSearch = $state('') const viewKey = rowCountKey(ownerSchema, ownerTable, ownerSig) const data = await getTableRows( ownerSchema, ownerTable, - wantsWindow ? WINDOW_PROBE : effectivePageSize, + wantsWindow ? probeSize : effectivePageSize, offset, { ...ownerQuery, keyset: keysetArg, @@ -7846,7 +7963,7 @@ let rowSearch = $state('') // total of 0, which reads as "cannot count" above, so it used to be asked // for the rest of its page - the same empty query a second time, on every // open and every return to its tab. - const probeExhausted = wantsWindow && fetched.length < WINDOW_PROBE + const probeExhausted = wantsWindow && fetched.length < probeSize const viewCount = wantsWindow ? (probeExhausted ? fetched.length @@ -7971,6 +8088,13 @@ let rowSearch = $state('') // one they are looking at. The grid re-emits its visible range as soon // as the new array lands, which asks for the right ones. if (!keepScroll) { + // A fresh view starts at the top. The last visible range belongs to + // whatever was on screen before (another table, another sort), and + // window 0's screenful-first check read it: rows 300-360 of the old + // view looked missing, so the rows the probe had just painted were + // fetched a second time ahead of the window. + _visStart = 0 + _visEnd = 0 const firstGap = _windowLoaded.size for (let w = firstGap; w <= firstGap + WINDOW_PREFETCH; w++) _windowQueue.push(w) pumpWindowQueue() diff --git a/src/lib/row-window.js b/src/lib/row-window.js index 8eb6344c..112a4362 100644 --- a/src/lib/row-window.js +++ b/src/lib/row-window.js @@ -11,10 +11,24 @@ * resident, what's in flight) lives in StudioShell. */ -/** Rows in the first, measuring fetch of a large load. */ -export const WINDOW_PROBE = 200 -/** Target payload for one window request. */ -export const WINDOW_TARGET_BYTES = 2_000_000 +/** + * Rows in the first, measuring fetch of a large load. It is also the first + * paint, so it is sized to a few screens rather than to the measurement: at + * 200 rows a table of 6.5 KB rows sent 1.3 MB before anything showed, 3.2 s + * at 10 Mbit. 100 rows still measures a row's weight well (row-window samples + * three of them) and covers about three screens of a tall window. + */ +export const WINDOW_PROBE = 100 +/** + * Target payload for one window request. + * + * 600 KB, down from 2 MB. A window is what a scroll waits on whenever the rows + * in view are not the screenful fetched first, and 2 MB was 3-4 s on a 5 Mbit + * home link: an 800-byte-a-row audit table sat on skeletons for 4.8 s at rows + * 54-83. 600 KB is under a second there and still a few thousand narrow rows, + * so a local or fast link pays a handful more round trips and nothing else. + */ +export const WINDOW_TARGET_BYTES = 600_000 export const WINDOW_ROWS_MIN = 100 export const WINDOW_ROWS_MAX = 10_000 /** Used when the payload can't be measured at all. */ @@ -30,8 +44,16 @@ export const WINDOW_ROWS_DEFAULT = 5_000 * single request is quick enough that the extra round-trips aren't worth it. */ export const WINDOW_THRESHOLD = 25_000 -/** …or heavier than this, however few rows it has. */ -export const WINDOW_HEAVY_BYTES = 8_000_000 +/** + * …or heavier than this, however few rows it has. + * + * 1.5 MB, down from 8 MB. Under the bar a view is the probe and then ONE + * request for the rest, and nothing past the first 200 rows shows until it + * lands: a 4,000-row table of 1.5 KB rows was a single 6 MB response, ten + * seconds at 5 Mbit. Over it, the view streams in windows (and, when small, + * fills in the background - see fillRemainingWindows in StudioShell). + */ +export const WINDOW_HEAVY_BYTES = 1_500_000 /** Rows kept resident on each side of the viewport. */ export const WINDOW_KEEP_ROWS = 80_000 diff --git a/src/lib/row-window.test.js b/src/lib/row-window.test.js index dbda71be..b8df6aaf 100644 --- a/src/lib/row-window.test.js +++ b/src/lib/row-window.test.js @@ -56,9 +56,11 @@ describe('pickWindowRows', () => { }) it('keeps one window near the byte target', () => { - // 20KB rows → ~2MB per window, whatever the row shape happens to be. - const bytes = 20_000 - expect(pickWindowRows(bytes) * bytes).toBeLessThan(4_000_000) + // 2KB rows → ~600KB per window, whatever the row shape happens to be: a + // window is what a scroll waits on, so it stays under a second at 5 Mbit. + const bytes = 2_000 + expect(pickWindowRows(bytes) * bytes).toBeLessThanOrEqual(600_000) + expect(pickWindowRows(bytes) * bytes).toBeGreaterThan(400_000) }) it('falls back to the default when the payload is unmeasurable', () => { @@ -79,6 +81,11 @@ describe('shouldWindow', () => { expect(shouldWindow({ rowCount: 10_000, bytesPerRow: 130 })).toBe(false) }) + it('streams a few thousand wide rows instead of one big response', () => { + // 4,000 rows of 1.5 KB is 6 MB: windowed, so rows show as they arrive. + expect(shouldWindow({ rowCount: 4_000, bytesPerRow: 1_500 })).toBe(true) + }) + it('never windows without an exact row count', () => { expect(shouldWindow({ rowCount: 1_000_000, bytesPerRow: 130, countKnown: false })).toBe(false) expect(shouldWindow({ rowCount: 0, bytesPerRow: 130 })).toBe(false)