cd4c62042a
Round 3 of benchmark-gated optimizations (benches/ROUND3.md; every change gated by a before/after benchmark — an AFTER that did not beat its BEFORE was to be rolled back; none needed it. Equivalence gates assert identical row sequences / byte-identical output on every behavior-preserving rewrite): DB hot paths (local PG16, EXPLAIN-verified): - Web-UI listing (list_resources_paged): cursor pushed INSIDE the folders/files UNION-ALL branches as sargable row-value comparisons with per-branch ORDER/LIMIT + two partial expression indexes (folder_id, LOWER(name), id). 20k-entry folder: 26.6 -> 1.3 ms/page (19.5x); other sort modes at parity or better. New migration 20260918000000. [benches/LISTING-KEYSET.md section in ROUND3] - Photos timeline (list_media_files): per-drive CROSS JOIN LATERAL top-N on the timeline index, joins moved above the top-N. 50k-photo library: 97.4 -> 1.6 ms/page (55.7x). The old "LIMIT stops the scan early" comment was refuted by EXPLAIN. - PROPFIND sub-folders (both DAV surfaces): keyset list_folders_batch off idx_folders_unique_name replaces COUNT(*) OVER() + LIMIT/OFFSET (5k dirs: 79.7 -> 17.9 ms full walk, 4.5x). Concurrency: - Basic-auth cache single-flight (moka try_get_with): 8 concurrent DAV connections at TTL expiry paid 8 Argon2id runs (2.6 s CPU + 8x64 MiB); now 1 (300 ms). Failed verifications remain uncached. - CachedBlobBackend per-hash single-flight + unique tmp names: 16 concurrent cold readers = 16 full remote downloads racing truncating writes on ONE deterministic .tmp (corruptible cache); now 1 download (16x less egress, 2.8x wall on a shared link) and torn files can never be renamed into the cache. I/O and allocations: - Chunk-assembly reads 64K -> 512K buffers (2.3x, 8x fewer syscalls); chunk-spool writes via BufWriter 512K (5.6x, 32x fewer syscalls). - S3/Azure put_blob_from_bytes_unsynced overrides: dedup settle no longer pays a HEAD probe per new chunk (2 RTT -> 1, 1.8x); Azure stops copying every chunk (Bytes -> Body, -0.44 ms - 4 MiB alloc per 4 MiB chunk). - Entity->DTO mapping: Arc<str> interning of closed-set display fields + common MIMEs, 1-alloc etag/size formatting, FolderDto moves instead of clones. File row: 11 -> 4 allocs; folder row: 11.8 -> 1 (2.1x faster). - CardDAV REPORT: deleted dead per-contact vCard pre-generation and the O(N^2) uid scan whose result was discarded (5k contacts: 55.7 -> 5.7 ms, 9.8x); byte-identical XML asserted. - Search-results cache: byte weigher + 32 MiB budget (OXICLOUD_SEARCH_CACHE_MAX_BYTES) replaces the 1000-ENTRY cap that let ~300 MiB of enriched rows sit in RSS; read latency parity. - Dropped aws-config + aws-smithy-types (zero references; -82 dep-graph nodes, three SDK stacks gone from every build). tokio "process" is now an explicit feature (was enabled transitively by aws-config). Frontend: - Cached Intl.DateTimeFormat keyed by (locale, options) in formatDate and 4 sibling callsites: 20k dates 2612 -> 51 ms (51.6x); vitest gate asserts output identity across locales and a 3x floor. Validation: cargo fmt + clippy --all-features --all-targets -D warnings clean; 518 unit + 548 integration-cfg tests green; new-shape endpoints smoke-tested end-to-end over HTTP (all 5 listing sort modes with cursor walks, WebDAV PROPFIND Depth-1, photos timeline, Basic-auth DAV login); frontend npm run check clean, new vitest gates green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EBsU2qEzny3A8WQUEuMNCr
265 lines
8.0 KiB
Rust
265 lines
8.0 KiB
Rust
//! PROPFIND subfolder-paging benchmark — LIMIT/OFFSET + COUNT(*) OVER() vs
|
|
//! keyset, mirroring the files-side PROPFIND-PAGING fix.
|
|
//!
|
|
//! The streaming PROPFIND walkers (native WebDAV + NC-DAV) page a folder's
|
|
//! subfolders via `list_folders_paginated`, whose query is
|
|
//! `COUNT(*) OVER() … ORDER BY name LIMIT $2 OFFSET $3` — every page
|
|
//! window-aggregates and rescans ALL N subfolders (the total is only used
|
|
//! for has_next), so a full walk is O(N²/page) row visits.
|
|
//!
|
|
//! The AFTER shape is the same keyset used for files: `name > $last ORDER BY
|
|
//! name LIMIT k`, served by the existing UNIQUE index
|
|
//! `idx_folders_unique_name (parent_id, name, drive_id) WHERE NOT is_trashed
|
|
//! AND parent_id IS NOT NULL` — no migration needed. has_next falls out of
|
|
//! `rows.len() == limit`.
|
|
//!
|
|
//! Equivalence gate: the drained name sequence must be identical.
|
|
//!
|
|
//! Run (needs Postgres up; reads DATABASE_URL from .env):
|
|
//! cargo run --release --features bench --example bench_folder_keyset
|
|
//! Tunables: BENCH_DIRS (5000), BENCH_PAGE (500), BENCH_REPS (5)
|
|
|
|
use std::env;
|
|
use std::time::Instant;
|
|
|
|
use sqlx::PgPool;
|
|
use sqlx::postgres::PgPoolOptions;
|
|
use uuid::Uuid;
|
|
|
|
fn env_or<T: std::str::FromStr>(key: &str, default: T) -> T {
|
|
env::var(key)
|
|
.ok()
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(default)
|
|
}
|
|
|
|
async fn seed(pool: &PgPool, dirs: usize) -> (Uuid, Uuid) {
|
|
let mut tx = pool.begin().await.expect("begin");
|
|
let drive_id: Uuid = sqlx::query_scalar(
|
|
"INSERT INTO storage.drives (kind, quota_bytes) VALUES ('shared', NULL) RETURNING id",
|
|
)
|
|
.fetch_one(&mut *tx)
|
|
.await
|
|
.expect("drive");
|
|
let folder_id: Uuid = sqlx::query_scalar(
|
|
"INSERT INTO storage.folders (name, path, lpath, drive_id)
|
|
VALUES ('bench_folder_keyset', '/bench_folder_keyset', 'bench_folder_keyset', $1)
|
|
RETURNING id",
|
|
)
|
|
.bind(drive_id)
|
|
.fetch_one(&mut *tx)
|
|
.await
|
|
.expect("folder");
|
|
sqlx::query("UPDATE storage.drives SET root_folder_id = $1 WHERE id = $2")
|
|
.bind(folder_id)
|
|
.bind(drive_id)
|
|
.execute(&mut *tx)
|
|
.await
|
|
.expect("stamp");
|
|
tx.commit().await.expect("commit");
|
|
|
|
sqlx::query(
|
|
"INSERT INTO storage.folders (name, path, lpath, parent_id, drive_id)
|
|
SELECT 'Dir_' || LPAD(i::text, 6, '0'),
|
|
'/bench_folder_keyset/Dir_' || LPAD(i::text, 6, '0'),
|
|
('bench_folder_keyset.d' || i)::ltree,
|
|
$1, $2
|
|
FROM generate_series(1, $3) AS i",
|
|
)
|
|
.bind(folder_id)
|
|
.bind(drive_id)
|
|
.bind(dirs as i32)
|
|
.execute(pool)
|
|
.await
|
|
.expect("dirs");
|
|
sqlx::query("ANALYZE storage.folders")
|
|
.execute(pool)
|
|
.await
|
|
.ok();
|
|
(drive_id, folder_id)
|
|
}
|
|
|
|
const COLS: &str = "id::text, name, path, parent_id::text, drive_id,
|
|
EXTRACT(EPOCH FROM created_at)::bigint,
|
|
EXTRACT(EPOCH FROM updated_at)::bigint,
|
|
EXTRACT(EPOCH FROM tree_modified_at)::bigint,
|
|
created_by, updated_by";
|
|
|
|
type Row = (
|
|
String,
|
|
String,
|
|
String,
|
|
Option<String>,
|
|
Uuid,
|
|
i64,
|
|
i64,
|
|
i64,
|
|
Option<Uuid>,
|
|
Option<Uuid>,
|
|
);
|
|
type RowWithTotal = (
|
|
String,
|
|
String,
|
|
String,
|
|
Option<String>,
|
|
Uuid,
|
|
i64,
|
|
i64,
|
|
i64,
|
|
Option<Uuid>,
|
|
Option<Uuid>,
|
|
i64,
|
|
);
|
|
|
|
/// OLD: production `list_folders_paginated` shape — window total + OFFSET.
|
|
async fn walk_offset(pool: &PgPool, parent: Uuid, page: i64) -> (Vec<String>, Vec<f64>) {
|
|
let mut offset = 0i64;
|
|
let mut names = Vec::new();
|
|
let mut times = Vec::new();
|
|
loop {
|
|
let t = Instant::now();
|
|
let rows: Vec<RowWithTotal> = sqlx::query_as(&format!(
|
|
"SELECT {COLS}, COUNT(*) OVER() AS total_count
|
|
FROM storage.folders
|
|
WHERE parent_id = $1::uuid AND NOT is_trashed
|
|
ORDER BY name
|
|
LIMIT $2 OFFSET $3"
|
|
))
|
|
.bind(parent)
|
|
.bind(page)
|
|
.bind(offset)
|
|
.fetch_all(pool)
|
|
.await
|
|
.expect("offset page");
|
|
times.push(t.elapsed().as_secs_f64() * 1000.0);
|
|
let n = rows.len();
|
|
names.extend(rows.into_iter().map(|r| r.1));
|
|
if (n as i64) < page {
|
|
break;
|
|
}
|
|
offset += n as i64;
|
|
}
|
|
(names, times)
|
|
}
|
|
|
|
/// NEW: keyset on the existing unique index; has_next = rows.len() == limit.
|
|
async fn walk_keyset(pool: &PgPool, parent: Uuid, page: i64) -> (Vec<String>, Vec<f64>) {
|
|
let mut after: Option<String> = None;
|
|
let mut names = Vec::new();
|
|
let mut times = Vec::new();
|
|
loop {
|
|
let t = Instant::now();
|
|
let rows: Vec<Row> = if let Some(a) = &after {
|
|
sqlx::query_as(&format!(
|
|
"SELECT {COLS}
|
|
FROM storage.folders
|
|
WHERE parent_id = $1::uuid AND NOT is_trashed AND name > $3
|
|
ORDER BY name
|
|
LIMIT $2"
|
|
))
|
|
.bind(parent)
|
|
.bind(page)
|
|
.bind(a)
|
|
.fetch_all(pool)
|
|
.await
|
|
} else {
|
|
sqlx::query_as(&format!(
|
|
"SELECT {COLS}
|
|
FROM storage.folders
|
|
WHERE parent_id = $1::uuid AND NOT is_trashed
|
|
ORDER BY name
|
|
LIMIT $2"
|
|
))
|
|
.bind(parent)
|
|
.bind(page)
|
|
.fetch_all(pool)
|
|
.await
|
|
}
|
|
.expect("keyset page");
|
|
times.push(t.elapsed().as_secs_f64() * 1000.0);
|
|
let n = rows.len();
|
|
after = rows.last().map(|r| r.1.clone());
|
|
names.extend(rows.into_iter().map(|r| r.1));
|
|
if (n as i64) < page {
|
|
break;
|
|
}
|
|
}
|
|
(names, times)
|
|
}
|
|
|
|
fn median(mut xs: Vec<f64>) -> f64 {
|
|
xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
|
xs[xs.len() / 2]
|
|
}
|
|
|
|
#[tokio::main(flavor = "multi_thread")]
|
|
async fn main() {
|
|
dotenvy::dotenv().ok();
|
|
let url = env::var("DATABASE_URL").expect("set DATABASE_URL");
|
|
let dirs: usize = env_or("BENCH_DIRS", 5_000);
|
|
let page: i64 = env_or("BENCH_PAGE", 500);
|
|
let reps: usize = env_or("BENCH_REPS", 5);
|
|
|
|
let pool = PgPoolOptions::new()
|
|
.max_connections(5)
|
|
.connect(&url)
|
|
.await
|
|
.expect("connect");
|
|
println!("seeding {dirs} subfolders (one-time)…");
|
|
let (drive_id, folder_id) = seed(&pool, dirs).await;
|
|
|
|
let (ref_names, _) = walk_offset(&pool, folder_id, page).await;
|
|
assert_eq!(ref_names.len(), dirs, "reference drain size");
|
|
|
|
println!("\n# full PROPFIND subfolder walk of a {dirs}-dir parent, {page}/page");
|
|
println!(
|
|
"{:<12} {:>11} {:>11} {:>8}",
|
|
"mode", "total ms", "p50 ms/pg", "vs OLD"
|
|
);
|
|
|
|
let mut failures = 0usize;
|
|
let mut base: Option<f64> = None;
|
|
for mode in ["OFFSET", "KEYSET"] {
|
|
let mut totals = Vec::with_capacity(reps);
|
|
let mut per_page: Vec<f64> = Vec::new();
|
|
for _ in 0..reps {
|
|
let t = Instant::now();
|
|
let (names, times) = if mode == "OFFSET" {
|
|
walk_offset(&pool, folder_id, page).await
|
|
} else {
|
|
walk_keyset(&pool, folder_id, page).await
|
|
};
|
|
totals.push(t.elapsed().as_secs_f64() * 1000.0);
|
|
if names != ref_names {
|
|
eprintln!("EQUIVALENCE FAILURE: {mode} drained a different sequence");
|
|
failures += 1;
|
|
}
|
|
per_page = times;
|
|
}
|
|
let ms = median(totals);
|
|
let speedup = base
|
|
.map(|b| format!("{:.1}x", b / ms))
|
|
.unwrap_or_else(|| "1.0x".into());
|
|
if base.is_none() {
|
|
base = Some(ms);
|
|
}
|
|
println!(
|
|
"{:<12} {:>11.1} {:>11.2} {:>8}",
|
|
mode,
|
|
ms,
|
|
median(per_page.clone()),
|
|
speedup
|
|
);
|
|
}
|
|
|
|
let _ = sqlx::query("DELETE FROM storage.drives WHERE id = $1")
|
|
.bind(drive_id)
|
|
.execute(&pool)
|
|
.await;
|
|
|
|
if failures > 0 {
|
|
eprintln!("\n{failures} equivalence failures — the NEW shape is NOT safe to adopt");
|
|
std::process::exit(1);
|
|
}
|
|
}
|