Files
CollabTable/PERFORMANCE_REPORT.md
T
Gabriel20xxandClaude Haiku 5.5 a84a36349b Fix critical and high audit findings
Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE):
- P-001 · Dashboard re-downloads the entire dataset every 5 seconds

Re-synced the vendored shared/ snapshot from shared commit 199a5ef.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-19 07:48:07 +00:00

100 lines
15 KiB
Markdown

# Performance Report — CollabTable
- **Project:** CollabTable
- **Path:** /workspace/Personal/Web/Originals/CollabTable
- **Analyzed:** 2026-10-16
- **Commit:** 6aec03f on main
- **Working tree:** clean (no uncommitted changes, no untracked files)
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
- **Updated:** 2026-10-19 — Critical and High findings handled in the working tree (not committed).
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). No tests, builds or linters were run; the analysis is static.
## Summary
| Severity | Count | Fixed | Not reproduced | Open |
|---|---:|---:|---:|---:|
| Critical | 0 | 0 | 0 | 0 |
| High | 2 | 1 | 0 | 1 |
| Medium | 5 | 0 | 0 | 5 |
| Low | 3 | 0 | 0 | 3 |
| Info | 1 | 0 | 0 | 1 |
Two structural costs dominate: the dashboard re-downloads the full database every 5 seconds, and sync writes row by row with several round trips per value inside one long transaction. Missing indexes and pagination will make both worse as data grows.
## Issues
### P-001 · Dashboard re-downloads the entire dataset every 5 seconds · **High** · Fixed
- **Location:** `backend/web.go:9-29` (four unpaginated queries), `backend/data.go:68-204` (no LIMIT in any query builder), `backend/web.go:74-76` (`no-store`), `frontend/src/lib/features/lists/listsData.svelte.js:4,10`, `frontend/src/lib/api.js:27-29`
- **Description:** `createOverviewData()` polls `/web/data` with `refetchInterval: 5000`. Each response contains every non-deleted list, every field, every item and every item value, with no pagination, no `since` filter and no HTTP caching (`Cache-Control: no-store`). The server already computes per-list effective update times (`web.go:31-72`), but the client has no way to use them to skip unchanged data. TanStack Query's default is to poll only while the tab is visible, so each open dashboard pays this cost.
- **Impact:** Transfer, JSON encoding and client re-rendering all scale with total data size rather than with the amount of change. With a few thousand items and several viewers this is continuous multi-megabyte traffic and repeated full re-renders.
- **Recommendation:** Serve changes incrementally with a `since` cursor (as sync already does), or add an ETag derived from the maximum `updatedat` and answer `304` when nothing changed, dropping `no-store` for that path. Compress the response (see P-006). Consider a longer interval or server push for the dashboard.
- **Status:** Fixed 2026-10-19 — `/web/data` now sends a weak ETag over the response data (the per-request timestamp is excluded), answers `304` when `If-None-Match` matches, and uses `Cache-Control: private, no-cache` instead of `no-store`, so an unchanged poll sends no body. A `max(updatedat)` validator was rejected because client-supplied timestamps can move backwards and hard deletes leave no trace. Residual: changed data is still sent in full, the server still runs the four queries on every poll, and browsers may now keep a private on-disk copy of the dashboard data, which `no-store` previously prevented. Files: `backend/web.go`, `backend/data.go` (stable tie-break order), `backend/web_test.go`.
### P-002 · Sync issues several statements per row inside one long transaction · **High** · Open
- **Location:** `backend/sync.go:61-209` (the transaction closure). For item values, `sync.go:172-207`: `listid` lookup (`:175`), `EXISTS` on items (`:185`), optional stub insert (`:193`), upsert (`:198`) and a notification insert (`:206`). Per-row upserts at `sync.go:64-79`, `:104-126`, `:149-164`. Request size is capped at 50 MB by `backend/server.go:253-259`.
- **Description:** Every list, field, item and value in a request is processed one at a time with separate statements. Each item value needs four to five round trips, plus a notification row per change, and the whole batch holds row locks until commit. There is no cap on the number of rows per request.
- **Impact:** An initial sync or a large offline push (potentially thousands of rows) becomes thousands of sequential round trips. The transaction stays open for the whole batch, and the 60-second `WriteTimeout` (`server.go:123`) can cut the request off. The device then retries and repeats the same work, and concurrent devices contend on the same rows.
- **Recommendation:** Batch the writes, using `pgx.Batch` or multi-row `INSERT ... SELECT FROM unnest(...)` upserts per table. Load the field-to-list map once per request instead of once per value. Insert notifications as one multi-row statement per request. Cap rows per request, return `413` above the cap, and have clients chunk their pushes.
- **Status:** Open 2026-10-19 — partly addressed: `backend/sync.go` now resolves each request's fields and items in two statements (`valueReferences`) instead of up to two lookups per value, which removes the per-value reads. Still needed: the list, field, item and value upserts and their notification inserts still run one statement at a time inside one transaction, so this needs `pgx.Batch` or `unnest` bulk upserts; the per-request row cap with `413` is a client-facing change and needs CollabTableAndroid to chunk pushes first. Not measured against PostgreSQL, since none is available in this environment.
### P-003 · No index on `updatedat`, so every delta query scans the table · **Medium**
- **Location:** `backend/db.go:40-189` (indexes exist only on `fields.listid`, `items.listid`, `item_values.itemid`, `item_values.fieldid`, and notifications `createdat` and `listid`, at `:83-86` and `:97-98`). Queries filtering on `updatedat`: `backend/data.go:75`, `:108`, `:145`, `:178`; sync calls at `backend/sync.go:220-235`.
- **Description:** Sync and `/web/data` filter with `updatedat >= $1`, but `lists`, `fields`, `items` and `item_values` have no index on `updatedat`. Rows are soft-deleted and never physically removed, so the tables only grow.
- **Impact:** Every sync from every device performs four full table scans, and the cost grows with history rather than with recent change volume.
- **Recommendation:** Add `CREATE INDEX IF NOT EXISTS` on `updatedat` for `lists`, `items`, `fields` and `item_values` in `initSchema`. Consider `(isdeleted, updatedat)` if soft-delete filtering is common in the same queries.
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium**
- **Location:** `backend/data.go:68-204` (`queryLists`, `queryFields`, `queryItems`, `queryValues`, none with LIMIT), `backend/data.go:228-235` (`GET /api/lists`), `backend/sync.go:216-248` (`since` is nil when `lastSync == 0`, so the full table is returned).
- **Description:** Collection endpoints return unbounded arrays. The first sync from any device (`lastSync == 0`) returns every list, field, item and value in the database in one response.
- **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients.
- **Recommendation:** Add keyset pagination (a `(updatedat, id)` cursor and a `limit` parameter) to the collection endpoints. For sync, return a `hasMore` flag and a cursor, and let the client loop until it is caught up.
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium**
- **Location:** `frontend/src/routes/lists/[id]/+page.svelte:94` (`itemValuesFor(overview.values, item.id)` runs once per visible row and scans every value in the database) and `:98` (`valueFor` per cell); `frontend/src/lib/components/lists/ListCard.svelte:7-8` (each card filters all fields and all items); `frontend/src/lib/features/lists/listHelpers.js:1-15` (linear `filter` and `find` with no index).
- **Description:** The helpers are linear scans over the complete data set, and they run for every visible row and card. Because each 5-second poll replaces the arrays, every derived value is recomputed on every poll.
- **Impact:** Cost per render is roughly visible rows times total values. With a large data set this appears as delayed input and scroll jank.
- **Recommendation:** Build lookup maps once per data change in a `$derived` (a `Map` keyed by `listId`, by `itemId`, and by `itemId + fieldId`). Pass pre-grouped slices into the card and row components. Rely on TanStack's structural sharing so unchanged data keeps its references.
### P-006 · No HTTP compression and no cache headers on JSON or static assets · **Medium**
- **Location:** `backend/server.go:118-125` (plain `http.Server`, no compression middleware), `backend/server.go:292-316` (`spaFileServer` sets no `Cache-Control`), `backend/web.go:74-76` (`no-store` on `/web/data`).
- **Description:** JSON responses (`/web/data`, `/api/sync`, `/api/lists`) are sent uncompressed. Static build output, including content-hashed Vite assets, is served with no cache-control, and the embedded filesystem provides no modification times for conditional requests.
- **Impact:** Large JSON bodies transfer several times more bytes than necessary, and browsers refetch the whole app bundle on each visit.
- **Recommendation:** Add gzip or brotli middleware, or enable it at the reverse proxy. Set `Cache-Control: public, max-age=31536000, immutable` for `_app/immutable/*` and `no-cache` for `index.html`. Add ETags for `/web/data` (see P-001).
### P-007 · Request bodies up to 50 MB are decoded into memory with no per-route limit · **Medium**
- **Location:** `backend/server.go:253-259` (`decodeJSON` uses `io.LimitReader(r.Body, 50*1024*1024)`), used by `backend/sync.go:46` and by the write handlers in `backend/data.go`.
- **Description:** Every write endpoint accepts up to 50 MB of JSON and decodes it fully into Go structs. `io.LimitReader` truncates silently, so an oversized body fails with a confusing decode error instead of `413`. These handlers have no concurrency cap, so each concurrent request can allocate its full decode buffer.
- **Impact:** A few concurrent large requests can exhaust memory. It is also an easy denial-of-service vector (see the rate-limiting note in the Security report).
- **Recommendation:** Use `http.MaxBytesReader` with per-route limits (for example 1 to 5 MB for single-entity writes, and a higher bound for sync), returning `413` when exceeded. Bound concurrent sync transactions with a semaphore sized below `DATABASE_MAX_CONNS`.
### P-008 · One notification row per changed row, on every write path · **Low**
- **Location:** `backend/sync.go:79`, `:126`, `:164`, `:206`; `backend/data.go:256`, `:302`, `:364`, `:418`, `:507`, `:561`, `:605`, `:621`; retention in `backend/db.go:212-230`; polling in `backend/web.go:92-141` (`LIMIT 500` at `:109`).
- **Description:** Each changed row inserts its own notification. A 1,000-value sync writes 1,000 extra rows, and each one is later read by the Android poller.
- **Impact:** Write amplification on the hot path and extra cleanup load. Clients polling 500 notifications at a time may need several polls to catch up after a bulk change.
- **Recommendation:** Coalesce notifications per list per request, so a sync produces one row per affected list. Alternatively, drop per-row notifications and rely on the `updatedat` delta.
### P-009 · Docker build context and cache layering can be tighter · **Low**
- **Location:** `docker/Dockerfile:34-35` (`COPY shared/backend/` happens before `go mod download`); `.dockerignore` excludes `.git`, `node_modules`, `data/` and `collabtable.db`, but not `CollabTableAndroid/`, `.github/` or `**/node_modules` under `shared/`.
- **Description:** Any edit under `shared/backend` invalidates the module-download layer, because the source is copied before `go mod download`. The build context also includes the whole Android project and CI files, which slows context transfer.
- **Impact:** Slower builds and avoidable cache misses in CI.
- **Recommendation:** Copy only `shared/backend/go.mod` and `go.sum` before `go mod download`, and copy the rest of `shared/backend` afterwards. Add `CollabTableAndroid/`, `.github/` and `**/node_modules` to `.dockerignore`.
### P-010 · No statement timeout or per-query budget on the database pool · **Low**
- **Location:** `shared/backend/postgres/postgres.go:114-121` (pool defaults: `MaxConns: 20`, no `statement_timeout`); `backend/sync.go:61` (the transaction runs under the request context).
- **Description:** Queries are bounded only by the request context. Nothing caps statement run time at the database, and a long sync transaction holds a pool connection for its full duration.
- **Impact:** A slow query or a large sync can hold one of 20 connections for longer than intended and starve other requests.
- **Recommendation:** Set `statement_timeout` (and optionally `lock_timeout`) as pool runtime parameters, and set `DATABASE_MAX_CONNS` explicitly for each environment. Combine this with the batching in P-002.
### P-011 · Checked, no issue found · **Info**
- **Location:** `shared/backend/authclient/client.go:116` (5-second HTTP client timeout on outbound identity calls); `docker/Dockerfile:41-47` (final stage is `FROM scratch`, runs as `65534`, and contains only the binary and CA bundle); `backend/db.go:83-98` (indexes on the foreign-key and list-scoped lookup columns, and on notification `createdat` for cleanup and polling).
- **Description:** Outbound identity calls have a timeout, the runtime image is minimal and contains no build tools, and the main lookup paths are indexed.
- **Impact:** None. Recorded so these areas are not re-checked.
- **Recommendation:** None.
## Notes
- Static analysis only. No tests, builds, Docker builds, lint runs or load tests were executed. Estimates come from code reading and should be confirmed with a benchmark on realistic data (for example a few thousand items across several devices).
- AuthGuard's own performance is outside this repository and was not analyzed.
- `shared/` was reviewed selectively: the parts CollabTable imports (`backend/auth`, `authclient`, `authproxy`, `coreconfig`, `postgres`, and the `carriernodeclient` construction). The shared web-ui was searched with grep only. The node, python and java packages were not reviewed.
- The frontend bundle was not measured. The web-ui is imported through its barrel (`import { Pagination } from '@gabriel20xx/web-ui'`), and whether that tree-shakes needs verification with a production build.
- No TODO, FIXME or HACK markers were found in `backend/` or `frontend/src/`.