Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/faster-table-loads.md
Original file line number Diff line number Diff line change
@@ -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.
69 changes: 26 additions & 43 deletions src-tauri/src/db/wide_columns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand All @@ -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 {
Expand Down Expand Up @@ -409,18 +399,14 @@ pub fn projection(all_columns: &[String], wide: &[WideColumn]) -> Option<String>
.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
Expand Down Expand Up @@ -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.
Expand Down
130 changes: 127 additions & 3 deletions src/lib/components/StudioShell.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2813,6 +2813,33 @@ let rowSearch = $state('')
let _schemaColumnsGen = 0
/** @type {Promise<void>} */
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<string, string[]>}
*/
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++
Expand All @@ -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<string, Array<{ name: string, type: string }>>} */
const next = {}
/** @type {Record<string, string[]>} */
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.
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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
}
}

/**
Expand Down Expand Up @@ -7689,13 +7747,64 @@ 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
if (windowed) evictFarWindows(firstW, lastW)
}, 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
Expand Down Expand Up @@ -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 = {
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
Loading
Loading