114 lines
18 KiB
Markdown
114 lines
18 KiB
Markdown
# Code Quality 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, Tailwind 4, TanStack Query) embedded in the Go binary; Android client (Kotlin, Jetpack Compose, Room, Retrofit/OkHttp); Docker; GitHub Actions.
|
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including the five test files), the frontend data layer, routes, list components and Vite config, the Android API client, preferences, sync repository and app Gradle file, `README.md`, `.github/workflows/*`, `docker/Dockerfile`, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper jar, generated build output, lock files (read for versions only), and the rest of `shared/`. The tracked SQLite files were inspected read-only from a copy. No tests, linters or builds were run.
|
|
|
|
## Summary
|
|
|
|
| Severity | Count |
|
|
|---|---:|
|
|
| Critical | 0 |
|
|
| High | 0 |
|
|
| Medium | 6 |
|
|
| Low | 8 |
|
|
| Info | 0 |
|
|
|
|
The backend is small and readable, but its transactional and delete logic is duplicated across the REST and sync paths and has drifted apart. A few error-handling assumptions are wrong, and the data layer has essentially no test coverage.
|
|
|
|
## Issues
|
|
|
|
### Q-001 · Notification errors inside transactions abort the sync they were meant to tolerate · **Medium**
|
|
- **Location:** `backend/notifications.go:51-57` (`ignoreNotificationError`); called inside transactions at `backend/sync.go:79`, `:126`, `:164`, `:206` and `backend/data.go:453`.
|
|
- **Description:** `ignoreNotificationError` says a failed notification "must never roll back the data mutation". When the notification insert runs inside the transaction, PostgreSQL marks the transaction as aborted after any failing statement, so the next statement fails and the commit cannot succeed. The error is only logged, which makes the function look like it tolerates the failure, but the whole sync then returns `500 Sync failed` after rolling back. The comment is wrong for these paths.
|
|
- **Impact:** A transient failure of a notification insert turns a successful write into a failed sync, and the client retries the same payload. Maintainers reading the comment will assume the opposite of what happens.
|
|
- **Recommendation:** Isolate the notification insert in a savepoint (a nested `tx.Begin` in pgx, or `SAVEPOINT` and `ROLLBACK TO SAVEPOINT`), or write notifications after commit. Update the comment to match the actual behavior.
|
|
|
|
### Q-002 · Delete semantics differ between REST endpoints and sync · **Medium**
|
|
- **Location:** `backend/data.go:309-321` (REST list delete sets only `lists.isdeleted`); `backend/sync.go:81-91` (sync list delete also cascades to fields, items and values); `backend/data.go:420-455` (field delete cascades only when no active fields remain); `backend/data.go:609-621` (item delete updates the item, then deletes its values in a separate statement whose error is discarded at `:620`, and skips the notification at `:618-619` if the re-read fails).
|
|
- **Description:** The same logical operations (delete a list, delete an item) leave different state depending on the entry point. A list deleted through REST keeps its fields, items and values active, while the same delete through sync removes the children. `/web/data` filters out deleted lists but still returns the active items and values that belong to them (`backend/web.go:31-72`). Item deletion is not atomic and can leave orphaned values if the second statement fails.
|
|
- **Impact:** The dashboard, the Android client and sync can disagree about what exists, and orphaned values are silently accepted.
|
|
- **Recommendation:** Implement `deleteList`, `deleteField` and `deleteItem` once, each inside a transaction, and call them from both REST and sync. Check every error.
|
|
|
|
### Q-003 · `handleSync` is a 200-line function, and cascade logic is duplicated · **Medium**
|
|
- **Location:** `backend/sync.go:45-249` (one function; the transaction closure spans `:61-209`). Duplicated cascade logic: `sync.go:128-143` and `backend/data.go:440-452`. Event-type selection repeated at `sync.go:72-78`, `:119-125` and `:157-163`. Default-value handling repeated at `sync.go:96-103` and `backend/data.go:349-354` and `:393-398`.
|
|
- **Description:** Upserts, notifications, cascades and response assembly all live in one closure. The business rules for deletion, defaults and event types are implemented twice, once in the sync handler and once in the REST handlers. Q-002 is a direct result of this duplication.
|
|
- **Impact:** Hard to test or change safely, and the two code paths have already diverged.
|
|
- **Recommendation:** Extract a small repository layer (`upsertList`, `upsertField`, `upsertItem`, `upsertValue`, `deleteList`, `deleteField`, `deleteItem`) shared by the REST handlers and sync, and keep the handlers as thin request and response adapters. Move event-type selection into one helper.
|
|
|
|
### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium**
|
|
- **Location:** `backend/routes_test.go:8-11` (registers routes with a nil database and asserts nothing); `backend/auth_test.go`, `env_test.go`, `models_test.go` and `sync_test.go` (cover env parsing, JSON timestamp parsing, timestamp normalization and the auth stub only); `.github/workflows/tests.yml` (Go job runs `go test ./...` with no Postgres service); the frontend has no unit tests (CI runs `npm run check` only); `CollabTableAndroid/app/src` has no test sources.
|
|
- **Description:** No test exercises `handleSync`, the list, field, item and value handlers, `/web/data`, the CORS wrapper, the SPA fallback, or the frontend helpers in `listHelpers.js`. The one route test runs without assertions.
|
|
- **Impact:** The most complex logic (sync merge, cascades, notification side effects, timestamp handling) is covered only by manual testing, so regressions like Q-001 and Q-002 are invisible.
|
|
- **Recommendation:** Add `httptest` integration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Give `routes_test.go` real assertions on methods and status codes. Add Vitest tests for `listHelpers.js`, and JVM unit tests for the Android sync merge logic.
|
|
|
|
### Q-005 · Setup documentation contradicts the configuration · **Medium**
|
|
- **Location:** `README.md:52` (`SECRET` marked as optional, default "unset (push endpoint refuses every caller)"); `README.md:70-79` (Quick Start `docker run` sets no `SECRET`); `README.md:55` (`COOKIE_SECURE` described as marking cookies `Secure`); `shared/backend/auth/proxy.go:359-361` and `:838-841`; `backend/auth.go:113-120`; `frontend/vite.config.js:38-41` (dev proxy forwards only `/web` and `/health`).
|
|
- **Description:** The auth service is built with `RequireSecret()` (`auth.go:118`). When `SECRET` is unset, `/api/auth/status` and every auth-gated route return `500 SECRET environment variable is not set.`, so the documented Quick Start produces a dashboard that cannot load. The README table also calls `SECRET` optional. The live session cookie's `Secure` and `SameSite` attributes come from AuthGuard (see Security S-013), so `COOKIE_SECURE` does not do what the README says. `npm run dev` proxies only `/web` and `/health`, but the dashboard calls `/api/auth/*` and `/api/tech-stack` (`frontend/src/lib/api.js`), so the dev server cannot reach the API.
|
|
- **Impact:** Operators who follow the docs get a deployment that fails or looks secure when it is not, and developers hit a confusing dev setup.
|
|
- **Recommendation:** Mark `SECRET` as required when auth is enabled, add it to the Quick Start, correct the `COOKIE_SECURE` description, and add `/api` to the Vite proxy.
|
|
|
|
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium**
|
|
- **Location:** `backend/sync.go:20-43` (client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the stored `updatedat`: `sync.go:64-69`, `:104-116`, `:149-156`, `:198-203`; the delta cursor filters on the stored value at `backend/data.go:75`, `:108`, `:145`, `:178`. Android: local edits stamped with device time (`CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt:148`), and the cursor is the server's `serverTimestamp` (`CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt:49-60`, `:283`).
|
|
- **Description:** Two related problems. (1) A device that edits offline stamps the change with an old local time. If another device has already advanced its cursor past that time, the `updatedat >= since` filter never returns the change to it. (2) Upserts overwrite the stored row whatever its `updatedat`, so an older change that arrives later replaces a newer one. The Android client mitigates (1) by forcing a full down-sync at app start (`SyncRepository.kt:122`), so the devices affected are those that stay open for a long time.
|
|
- **Impact:** Silent divergence between devices, and lost updates when two devices edit the same row offline. Dashboard users see stale data until a device restarts.
|
|
- **Recommendation:** Assign server-side change tokens (a monotonically increasing sequence, or the server receive time) to every write and use that as the cursor, keeping client `updatedat` for display only. Alternatively, make each upsert conditional on `EXCLUDED.updatedat` being newer than the stored value, and document the last-writer-wins rule.
|
|
|
|
### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low**
|
|
- **Location:** `backend/data.go:248-255` (duplicate list id returns `500 Failed to create list` rather than `409`); `backend/data.go:549-558` (an item value for a missing item or field fails on a foreign key and returns `500`); `backend/data.go:589-607` (`PUT /api/items/{id}` accepts a body but only bumps `updatedat`, ignoring the body); `backend/server.go:292-316` (unknown `/api/...` paths return `index.html` with `200`).
|
|
- **Description:** Client errors are reported as server errors, one endpoint documents a body it does not use, and unknown API paths get HTML with a success status.
|
|
- **Impact:** Clients cannot distinguish retryable from permanent failures, and an API mistake returns a web page instead of an error.
|
|
- **Recommendation:** Map unique and foreign-key violations (`pgconn.PgError` codes `23505` and `23503`) to `409` and `422`. Make `PUT /api/items/{id}` either apply the documented fields or be removed. Return JSON `404` for unmatched `/api/` paths before the SPA fallback.
|
|
|
|
### Q-008 · Dead code and unused wiring · **Low**
|
|
- **Location:** `backend/notifications.go:59-61` (`isNoRows` has no callers); `backend/server.go:38` and `:96-106` (the `carrierNode` client is built, stored and never used, and it holds the internal secret); `backend/db.go:111-140` and `:165-169` (retired auth tables are still created on every start); `backend/db.go:197-210` (session-pruning goroutine for those retired tables).
|
|
- **Description:** Dead helpers and an unused client remain in place. The retired tables are still managed by startup code even though nothing reads them.
|
|
- **Impact:** Noise for maintainers, and a secret held in memory for no purpose.
|
|
- **Recommendation:** Remove `isNoRows`. Construct the CarrierNode client only when a feature uses it. Drop the session-pruning goroutine, or document why it stays.
|
|
|
|
### Q-009 · Several failures are discarded without a comment on the risk · **Low**
|
|
- **Location:** `backend/data.go:424` and `:587` (`_ = decodeJSON(...)` on DELETE and PUT with an optional body); `backend/data.go:620` (`_, _ =` on the item value delete); `backend/data.go:618-619` (a failed item re-read silently skips the notification); `backend/sync.go:211` (raw database error text is logged, which can include values).
|
|
- **Description:** Errors are ignored in several places. The `decodeJSON` ignores are reasonable for optional bodies, but `data.go:620` guards data integrity, and the others hide failures from operators.
|
|
- **Impact:** Silent inconsistency (see Q-002) and harder debugging.
|
|
- **Recommendation:** Check and return the error from the value delete. Document the intentional `decodeJSON` ignores, or return `400` on a malformed body. Log errors with a request identifier rather than raw values.
|
|
|
|
### Q-010 · CI does not cover shared code, lint is partial, and Node versions disagree · **Low**
|
|
- **Location:** `.github/workflows/tests.yml` and `.github/workflows/lint.yml` `paths:` filters include `backend/**` and `frontend/**` but not `shared/**`, although `backend/go.mod` replaces the shared module with `../shared/backend` (`docker.yml` does include `shared/**`); `.github/workflows/lint.yml:41` (`node-version: '20'`) against `tests.yml:64` (`'22'`), `docker/Dockerfile:4` (`node:22-alpine`) and `README.md:85` (`Node.js 22+`); no Go lint job (`gofmt`, `go vet`, `golangci-lint`); the `format:check` script in `frontend/package.json` is not run; Android has no CI (acknowledged in the README).
|
|
- **Description:** A breaking change in `shared/backend` does not trigger the Go test job on push or pull request, and lint runs on Node 20 while everything else uses 22.
|
|
- **Impact:** Breakage in the shared library can reach `main` untested by push-triggered checks. The Docker build compiles it, but does not run its tests.
|
|
- **Recommendation:** Add `shared/backend/**` and `shared/packages/web-ui/**` to the Go and frontend workflow paths. Standardize on Node 22. Add `gofmt -l` and `go vet` to the Go job, and `npm run format:check` to lint.
|
|
|
|
### Q-011 · Unpinned and inconsistent dependency declarations · **Low**
|
|
- **Location:** `frontend/package.json` `devDependencies` and `dependencies` blocks (21 entries use `"latest"`, including `svelte`, `@sveltejs/kit`, `vite` and `@tanstack/svelte-query`); `.github/workflows/tests.yml:70` (web-ui installed with `--no-package-lock`); `CollabTableAndroid/app/build.gradle` (`compose-bom:2024.06.00` for the app but `2023.10.01` for `androidTestImplementation`, and `retrofit` declared as both `implementation` and `kapt`).
|
|
- **Description:** `"latest"` specifiers make the declared range meaningless and rely entirely on the lock file being respected. CI installs web-ui without a lock file. The Android app and test dependency sets use different Compose BOMs.
|
|
- **Impact:** Upgrades happen implicitly whenever the lock is regenerated, and app and test builds can resolve different Compose versions.
|
|
- **Recommendation:** Pin ranges (for example a caret range around the locked Svelte 5.56.8), commit the lock, and use `npm ci` for web-ui in CI. Align the Compose BOM and remove the redundant `kapt` Retrofit line.
|
|
|
|
### Q-012 · Release build has minification disabled · **Low**
|
|
- **Location:** `CollabTableAndroid/app/build.gradle:30` (`minifyEnabled false` in the `release` build type).
|
|
- **Description:** The release build ships unshrunk, unobfuscated code, and `proguard-rules.pro` has no effect because minification is off.
|
|
- **Impact:** Larger APK, and easier reverse engineering of the sync protocol.
|
|
- **Recommendation:** Enable `minifyEnabled true` and `shrinkResources true` for release, then verify with a release build and the Gson and Retrofit keep rules.
|
|
|
|
### Q-013 · Mutable singleton in the Android API client is not synchronized · **Low**
|
|
- **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:15-18` (mutable `baseUrl`, `retrofit` and `context`); `:119-137` (`initialize` and `setBaseUrl` rebuild Retrofit); `:139-145` (the `api` getter builds Retrofit lazily).
|
|
- **Description:** The singleton's fields are written from settings and read from background sync work without synchronization or `@Volatile`, and the lazy getter can build Retrofit twice.
|
|
- **Impact:** Possibly a stale base URL or a duplicate client during a settings change. This needs verification by changing the URL while a sync is running.
|
|
- **Recommendation:** Guard the state with a lock or `@Volatile`, or make the base URL an immutable value that is rebuilt through a single factory driven by a `StateFlow`.
|
|
|
|
### Q-014 · Stale and junk artifacts are tracked in the repository · **Low**
|
|
- **Location:** `backend/data/collabtable.db` (69,632-byte SQLite file; all five tables have zero rows and a pre-migration camelCase schema); `backend/collabtable.db` (0 bytes); `CollabTableAndroid/build-errors.txt` (contains only an interrupt marker); `CollabTableAndroid/build-output.txt` (4.8 KB build log); root `.gitignore` (no `*.db` or build-log rule).
|
|
- **Description:** Database files and build logs are committed. The SQLite file is a leftover from the Node-era schema, and the Go server uses PostgreSQL only. No credentials or user data were found in them.
|
|
- **Impact:** Confusing for contributors, and a risk if real data is ever saved there.
|
|
- **Recommendation:** Remove the tracked files, add ignore rules for `*.db` and `build-*.txt`, and keep only the placeholder `backend/web/.gitkeep`.
|
|
|
|
## Notes
|
|
- Static review only. No tests, linters, Go or Node builds, or Gradle runs were executed. Test coverage was assessed by reading the `_test.go` files and the CI workflows.
|
|
- Checked and clean: no `{@html}`, `innerHTML` or `eval` in the dashboard; error wrapping in `backend/db.go` and the auth helpers is consistent; `shared/backend/postgres/postgres.go:216-235` (`WithTx`) rolls back through a deferred call on every path; no TODO, FIXME or HACK markers in `backend/` or `frontend/src/`.
|
|
- `map[string]any` is used for several ad hoc response bodies (`backend/web.go:77-89`, `backend/data.go:464` and `:623`). That is acceptable for these responses, and no weakly typed data flows through the core domain types.
|
|
- `shared/` was reviewed selectively. Two items in it are outside CollabTable's runtime and are noted for the shared package owners rather than counted here: `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify` (which disables WebSocket origin checks) when the allowed origin is `*`, and the package is not imported by CollabTable.
|