perf: round 10 — auth alloc purge, parent-herd batching, query-shape pack, NC 304s

Benchmark-gated (benches/ROUND10.md; every change carries a BEFORE/AFTER
harness with equivalence/safety gates — two designs were rejected or
rewritten by their own benches before adoption):

- Auth hot path: TokenClaims/CurrentUser display fields to Arc<str>, role
  to inline SmolStr end-to-end (Bearer, cookie, Basic-auth cache) — 4→1
  allocs per authenticated request, 3→0 per warm DAV request; JWT
  Encoding/Decoding/Validation built once.
- Cold shared-album herd: leader-inline parent batching in PgAclEngine
  (+ cascade try_get_with single-flight) — 100→2 parent queries per
  100-thumb cold herd, herd wall 1.9x, sequential + warm paths unchanged,
  all ROUND8/9 safety gates plus new herd-equivalence gates.
- Query-shape pack: share download double-fetch 2→1 (2.18x), contact-group
  COUNT(*) 14.9x, save_faces UNNEST 3.9x, playlist reorder UNNEST 63.7x
  (now atomic), search files∥folders join! 1.45x, move drive-lookup join!
  2.14x, trash partial (drive_id, trashed_at) indexes, CalDAV event-gate
  narrow read, favorites/recents binary-decode port, dead count_files
  removed.
- NC surface: preview + avatar honour If-None-Match (e2e: 5 KB and 197 KB
  → 0 bytes per revalidation), avatar WebP→PNG transcode memoised,
  PROPFIND/trashbin integer+date emits on stack formatters, folder-header
  enrichment join!, chunk-PUT retry stat folded into create_new open.
- common::fmt integer rendering rewritten on the std 2-digit LUT after the
  round's own bench caught the div-loop losing to to_string (16.1 ns vs
  22.5; speeds every prior-round call site).
- Micro-pack: WebDAV scope probe borrow-only, ShareService base_url
  snapshot, cookie_secure OnceLock, Arc'd AES-GCM cipher, stack request-id,
  tantivy analyzer clone dropped.
- SPA: search stale-guard + AbortController (10→1 completed round-trips,
  stale-clobber gone), getFolder in-flight dedup, gridColumns matchMedia
  hoist (10k→0 style reads).

Backend: cargo fmt + clippy -D warnings clean, 524 tests green.
Frontend: npm run check clean, 301 vitest green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018DdM7V7M3QPW7HEHg3gLov
This commit is contained in:
Claude
2026-07-18 20:33:50 +00:00
parent 4fe429a109
commit c51af68432
64 changed files with 3452 additions and 442 deletions
@@ -213,6 +213,17 @@ impl CalendarEventRepository for CalendarEventPgRepository {
Ok(events)
}
async fn find_calendar_id_by_event_id(&self, id: &Uuid) -> CalendarEventRepositoryResult<Uuid> {
sqlx::query_scalar("SELECT calendar_id FROM caldav.calendar_events WHERE id = $1")
.bind(id)
.fetch_optional(&*self.pool)
.await
.map_err(|e| {
DomainError::database_error(format!("Failed to get event calendar id: {}", e))
})?
.ok_or_else(|| DomainError::not_found("Calendar Event", id.to_string()))
}
async fn find_event_by_id(&self, id: &Uuid) -> CalendarEventRepositoryResult<CalendarEvent> {
let row = sqlx::query(
r#"
@@ -177,6 +177,20 @@ impl ContactGroupRepository for ContactGroupPgRepository {
Ok(())
}
async fn count_contacts_in_group(&self, group_id: &Uuid) -> ContactRepositoryResult<i64> {
sqlx::query_scalar("SELECT COUNT(*) FROM carddav.group_memberships WHERE group_id = $1")
.bind(group_id)
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::new(
ErrorKind::InternalError,
"ContactGroup",
format!("Failed to count contacts in group: {}", e),
)
})
}
async fn get_contacts_in_group(
&self,
group_id: &Uuid,
@@ -115,29 +115,70 @@ impl FaceRepository for FacePgRepository {
if faces.is_empty() {
return Ok(());
}
let mut tx = self.pool.begin().await.map_err(|e| db_err("begin", e))?;
// One multi-row INSERT over parallel UNNEST arrays instead of one
// round-trip per face — a group photo yields many faces per indexed
// image. The `bbox` float4[] can't ride an array-of-arrays through
// unnest (PG flattens), so its 4 components travel as 4 parallel
// arrays and are reassembled server-side. A single statement is
// atomic on its own; the per-row transaction wrapper is gone.
let n = faces.len();
let mut ids = Vec::with_capacity(n);
let mut file_ids = Vec::with_capacity(n);
let mut user_ids = Vec::with_capacity(n);
let mut person_ids: Vec<Option<Uuid>> = Vec::with_capacity(n);
let (mut bx, mut by, mut bw, mut bh) = (
Vec::with_capacity(n),
Vec::with_capacity(n),
Vec::with_capacity(n),
Vec::with_capacity(n),
);
let mut det_scores = Vec::with_capacity(n);
let mut qualities: Vec<Option<f32>> = Vec::with_capacity(n);
let mut embeddings = Vec::with_capacity(n);
let mut blob_hashes: Vec<Option<&str>> = Vec::with_capacity(n);
for f in faces {
sqlx::query(
r#"
INSERT INTO faces.faces
(id, file_id, user_id, person_id, bbox, det_score, quality, embedding, blob_hash)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
"#,
)
.bind(f.id)
.bind(f.file_id)
.bind(f.user_id)
.bind(f.person_id)
.bind(f.bbox.to_array())
.bind(f.det_score)
.bind(f.quality)
.bind(embedding_to_bytes(&f.embedding))
.bind(f.blob_hash.as_deref())
.execute(&mut *tx)
.await
.map_err(|e| db_err("save_faces", e))?;
ids.push(f.id);
file_ids.push(f.file_id);
user_ids.push(f.user_id);
person_ids.push(f.person_id);
bx.push(f.bbox.x);
by.push(f.bbox.y);
bw.push(f.bbox.w);
bh.push(f.bbox.h);
det_scores.push(f.det_score);
qualities.push(f.quality);
embeddings.push(embedding_to_bytes(&f.embedding));
blob_hashes.push(f.blob_hash.as_deref());
}
tx.commit().await.map_err(|e| db_err("commit", e))?;
sqlx::query(
r#"
INSERT INTO faces.faces
(id, file_id, user_id, person_id, bbox, det_score, quality, embedding, blob_hash)
SELECT t.id, t.file_id, t.user_id, t.person_id,
ARRAY[t.bx, t.by, t.bw, t.bh]::real[],
t.det_score, t.quality, t.embedding, t.blob_hash
FROM unnest($1::uuid[], $2::uuid[], $3::uuid[], $4::uuid[],
$5::real[], $6::real[], $7::real[], $8::real[],
$9::real[], $10::real[], $11::bytea[], $12::text[])
AS t(id, file_id, user_id, person_id,
bx, by, bw, bh, det_score, quality, embedding, blob_hash)
"#,
)
.bind(&ids)
.bind(&file_ids)
.bind(&user_ids)
.bind(&person_ids)
.bind(&bx)
.bind(&by)
.bind(&bw)
.bind(&bh)
.bind(&det_scores)
.bind(&qualities)
.bind(&embeddings)
.bind(&blob_hashes)
.execute(self.pool.as_ref())
.await
.map_err(|e| db_err("save_faces", e))?;
Ok(())
}
@@ -24,18 +24,21 @@ impl FavoritesPgRepository {
impl FavoritesRepositoryPort for FavoritesPgRepository {
async fn get_favorites(&self, user_id: Uuid) -> Result<Vec<FavoriteItemDto>> {
// `id`/`user_id`/`parent_id` decode as binary UUIDs (16 B on the wire,
// no server-side `::TEXT` cast) and render app-side — the ROUND6 §10
// pattern the two legacy listing methods here never picked up.
let rows = sqlx::query(
r#"
SELECT
uf.id::TEXT AS "id",
uf.user_id::TEXT AS "user_id",
uf.id AS "id",
uf.user_id AS "user_id",
uf.item_id AS "item_id",
uf.item_type AS "item_type",
uf.created_at AS "created_at",
COALESCE(f.name, fld.name) AS "item_name",
f.size AS "item_size",
f.mime_type AS "item_mime_type",
COALESCE(f.folder_id::TEXT, fld.parent_id::TEXT) AS "parent_id",
COALESCE(f.folder_id, fld.parent_id) AS "parent_id",
COALESCE(f.updated_at, fld.updated_at) AS "modified_at",
CASE
WHEN uf.item_type = 'folder' THEN fld.path
@@ -70,15 +73,19 @@ impl FavoritesRepositoryPort for FavoritesPgRepository {
.iter()
.map(|row| {
FavoriteItemDto {
id: row.get("id"),
user_id: row.get("user_id"),
id: row.get::<i32, _>("id").to_string(),
user_id: row.get::<Uuid, _>("user_id").to_string(),
item_id: row.get("item_id"),
item_type: row.get("item_type"),
created_at: row.get("created_at"),
item_name: row.try_get("item_name").ok(),
item_size: row.try_get("item_size").ok(),
item_mime_type: row.try_get("item_mime_type").ok(),
parent_id: row.try_get("parent_id").ok(),
parent_id: row
.try_get::<Option<Uuid>, _>("parent_id")
.ok()
.flatten()
.map(|u| u.to_string()),
modified_at: row.try_get("modified_at").ok(),
item_path: row.try_get("item_path").ok(),
// Temporary defaults; with_display_fields() computes the real values
@@ -1394,19 +1394,6 @@ impl FileReadPort for FileBlobReadRepository {
Ok((files, total_count))
}
/// Count files matching the search criteria (without loading them).
async fn count_files(
&self,
folder_id: Option<&str>,
criteria: &SearchCriteriaDto,
caller_id: Uuid,
) -> Result<usize, DomainError> {
let (_, count) = self
.search_files_paginated(folder_id, criteria, caller_id)
.await?;
Ok(count)
}
#[allow(clippy::type_complexity)]
async fn suggest_files_by_name(
&self,
@@ -544,17 +544,27 @@ impl PlaylistItemRepository for PlaylistItemPgRepository {
playlist_id: &Uuid,
item_ids: &[Uuid],
) -> PlaylistItemRepositoryResult<()> {
for (index, item_id) in item_ids.iter().enumerate() {
sqlx::query(
"UPDATE audio.playlist_items SET position = $2 WHERE id = $1 AND playlist_id = $3",
)
.bind(item_id)
.bind(index as i32)
.bind(playlist_id)
.execute(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to reorder: {}", e)))?;
if item_ids.is_empty() {
return Ok(());
}
// One UNNEST-driven UPDATE instead of one autocommit round-trip per
// track — a full drag-reorder of an N-track playlist was N statements
// (and non-atomic: a mid-loop failure left a half-applied order).
// `WITH ORDINALITY` numbers the ids in array order, 1-based, so
// `ord - 1` reproduces the historical 0-based positions.
sqlx::query(
r#"
UPDATE audio.playlist_items AS pi
SET position = (t.ord - 1)::int
FROM unnest($1::uuid[]) WITH ORDINALITY AS t(id, ord)
WHERE pi.id = t.id AND pi.playlist_id = $2
"#,
)
.bind(item_ids)
.bind(playlist_id)
.execute(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to reorder: {}", e)))?;
Ok(())
}
@@ -21,18 +21,20 @@ impl RecentItemsPgRepository {
impl RecentItemsRepositoryPort for RecentItemsPgRepository {
async fn get_recent_items(&self, user_id: Uuid, limit: i32) -> Result<Vec<RecentItemDto>> {
// Binary UUID decode + app-side render (ROUND6 §10 pattern) — no
// server-side `::TEXT` casts, 16 B per id on the wire instead of 36.
let rows = sqlx::query(
r#"
SELECT
ur.id::TEXT AS "id",
ur.user_id::TEXT AS "user_id",
ur.id AS "id",
ur.user_id AS "user_id",
ur.item_id AS "item_id",
ur.item_type AS "item_type",
ur.accessed_at AS "accessed_at",
COALESCE(f.name, fld.name) AS "item_name",
f.size AS "item_size",
f.mime_type AS "item_mime_type",
COALESCE(f.folder_id::TEXT, fld.parent_id::TEXT) AS "parent_id",
COALESCE(f.folder_id, fld.parent_id) AS "parent_id",
CASE
WHEN ur.item_type = 'folder' THEN fld.path
WHEN ur.item_type = 'file' THEN COALESCE(pfld.path || '/' || f.name, f.name)
@@ -67,15 +69,19 @@ impl RecentItemsRepositoryPort for RecentItemsPgRepository {
.iter()
.map(|row| {
RecentItemDto {
id: row.get("id"),
user_id: row.get("user_id"),
id: row.get::<i32, _>("id").to_string(),
user_id: row.get::<Uuid, _>("user_id").to_string(),
item_id: row.get("item_id"),
item_type: row.get("item_type"),
accessed_at: row.get("accessed_at"),
item_name: row.try_get("item_name").ok(),
item_size: row.try_get("item_size").ok(),
item_mime_type: row.try_get("item_mime_type").ok(),
parent_id: row.try_get("parent_id").ok(),
parent_id: row
.try_get::<Option<Uuid>, _>("parent_id")
.ok()
.flatten()
.map(|u| u.to_string()),
item_path: row.try_get("item_path").ok(),
// Temporary defaults; with_display_fields() computes the real values
icon_class: String::new(),