24 KiB
Code Quality Report — CollabTable
- Project: CollabTable
- Path: /workspace/Personal/Web/Originals/CollabTable
- Analyzed: 2026-10-16
- Commit:
6aec03fon main - Working tree: contains uncommitted changes from the earlier and current medium passes.
- Updated: 2026-10-20 — Q-006 now uses a server-side change token; Q-004 remains partly open because its Android JVM test and PostgreSQL integration tests could not be run here.
- 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 tests), 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 ofshared/. The tracked SQLite files were inspected read-only from a copy. Verification commands and results are below.
Summary
| Severity | Count | Fixed | Not reproduced | Open |
|---|---|---|---|---|
| Critical | 0 | 0 | 0 | 0 |
| High | 0 | 0 | 0 | 0 |
| Medium | 6 | 5 | 0 | 1 |
| Low | 8 | 0 | 0 | 8 |
| Info | 0 | 0 | 0 | 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 · Fixed
- Location:
backend/notifications.go:51-57(ignoreNotificationError); called inside transactions atbackend/sync.go:79,:126,:164,:206andbackend/data.go:453. - Description:
ignoreNotificationErrorsays 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 returns500 Sync failedafter 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.Beginin pgx, orSAVEPOINTandROLLBACK TO SAVEPOINT), or write notifications after commit. Update the comment to match the actual behavior. - Status: Fixed 2026-10-19 — Notification inserts inside a transaction now run in a savepoint (
enqueueNotificationInTx), so a failed insert rolls back only the notification and the data change still commits. Each such notification adds two statements (savepoint and release). Files: backend/notifications.go, backend/sync.go, backend/data.go.
Q-002 · Delete semantics differ between REST endpoints and sync · Medium · Fixed
- Location:
backend/data.go:309-321(REST list delete sets onlylists.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-619if 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/datafilters 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,deleteFieldanddeleteItemonce, each inside a transaction, and call them from both REST and sync. Check every error. - Status: Fixed 2026-10-19 — REST and sync now share
cascadeDeleteList,cascadeDeleteFieldandcascadeDeleteItem, each delete runs in one transaction, and the value-delete error is no longer discarded. REST list deletes now cascade to fields, items and values as sync already did, which is a client-visible change for REST callers. Files: backend/data.go, backend/sync.go.
Q-003 · handleSync is a 200-line function, and cascade logic is duplicated · Medium · Fixed
- Location:
backend/sync.go:45-249(one function; the transaction closure spans:61-209). Duplicated cascade logic:sync.go:128-143andbackend/data.go:440-452. Event-type selection repeated atsync.go:72-78,:119-125and:157-163. Default-value handling repeated atsync.go:96-103andbackend/data.go:349-354and: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. - Status: Fixed 2026-10-19 —
handleSyncis now a thin adapter overapplySyncRequestand the per-tableapplyLists,applyFields,applyItemsandapplyValueshelpers. The cascades (cascadeDeleteList,cascadeDeleteField,cascadeDeleteItem),fieldDefaultsandupsertValueare shared by REST and sync, and sync picks its event type through one helper (changeEventType). The REST list, field and item create and update handlers keep their own SQL on purpose, because a plainINSERTrejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go.
Q-004 · Core data layer has no tests, and CI never starts a database · Medium · Open
- Location:
backend/db_test.goand.github/workflows/tests.yml(database-backed tests and a PostgreSQL service);frontend/src/lib/api.test.jsand thenode:testsuite;CollabTableAndroid/app/src/test/java/com/collabtable/app/data/repository/SyncPageProgressTest.kt(new JVM test, not yet run here). - Description: Backend and frontend coverage now exercises core paths, but local database-backed tests need PostgreSQL and the Android sync-page test has not been compiled or run. There is no Android CI job. The new coverage still needs a successful database and JVM execution.
- 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
httptestintegration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Giveroutes_test.goreal assertions on methods and status codes. Add Vitest tests forlistHelpers.js, and JVM unit tests for the Android sync merge logic. - Status: Open 2026-10-20 — Partly fixed: route and middleware tests assert behavior; PostgreSQL-backed tests now cover sync, pagination, change-token backfill, membership isolation, cascades, values, notifications,
/web/dataand tokens; frontend tests cover list helpers and credential proof forwarding; andSyncPageProgressTest.ktcovers the Android page loop. The PostgreSQL tests skip locally becauseTEST_DATABASE_URLis unset and no local PostgreSQL binaries are available. The workflow defines a PostgreSQL service but was not run here. Java and Gradle are unavailable, so the JVM test remains uncompiled and unrun; no Android CI job runs it.
Q-005 · Setup documentation contradicts the configuration · Medium · Fixed
- Location:
README.md:52(SECRETmarked as optional, default "unset (push endpoint refuses every caller)");README.md:70-79(Quick Startdocker runsets noSECRET);README.md:55(COOKIE_SECUREdescribed as marking cookiesSecure);shared/backend/auth/proxy.go:359-361and:838-841;backend/auth.go:113-120;frontend/vite.config.js:38-41(dev proxy forwards only/weband/health). - Description: The auth service is built with
RequireSecret()(auth.go:118). WhenSECRETis unset,/api/auth/statusand every auth-gated route return500 SECRET environment variable is not set., so the documented Quick Start produces a dashboard that cannot load. The README table also callsSECREToptional. The live session cookie'sSecureandSameSiteattributes come from AuthGuard (see Security S-013), soCOOKIE_SECUREdoes not do what the README says.npm run devproxies only/weband/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
SECRETas required when auth is enabled, add it to the Quick Start, correct theCOOKIE_SECUREdescription, and add/apito the Vite proxy. - Status: Fixed 2026-10-19 — README and backend README now mark
SECRETas required unlessAUTH_DISABLED=true, add it to the Quick Start, correct theCOOKIE_SECUREdescription, and documentALLOWED_ORIGINS; the Vite dev proxy now forwards/api. Files: README.md, backend/README.md, frontend/vite.config.js.
Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · Medium · Fixed
- Location:
backend/sync.go:20-43(client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the storedupdatedat:sync.go:64-69,:104-116,:149-156,:198-203; the delta cursor filters on the stored value atbackend/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'sserverTimestamp(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 >= sincefilter never returns the change to it. (2) Upserts overwrite the stored row whatever itsupdatedat, 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
updatedatfor display only. Alternatively, make each upsert conditional onEXCLUDED.updatedatbeing newer than the stored value, and document the last-writer-wins rule. - Status: Fixed 2026-10-20 — Every list, field, item and value write now receives a monotonic server
change_token; startup backfills existing rows. Sync reads a repeatable-read snapshot and returns a bounded page withnextSyncToken; Android follows all pages and saves the cursor after completion. Client timestamps remain metadata and govern stale-write handling. Existing clients must update because requests withoutlastSyncTokennow receive 400. PostgreSQL runtime tests are written but skipped locally; see Verification. Files:backend/db.go,backend/models.go,backend/sync.go,CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt,CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt.
Q-007 · Validation and error mapping return misleading status codes and contract drift · Low
- Location:
backend/data.go:248-255(duplicate list id returns500 Failed to create listrather than409);backend/data.go:549-558(an item value for a missing item or field fails on a foreign key and returns500);backend/data.go:589-607(PUT /api/items/{id}accepts a body but only bumpsupdatedat, ignoring the body);backend/server.go:292-316(unknown/api/...paths returnindex.htmlwith200). - 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.PgErrorcodes23505and23503) to409and422. MakePUT /api/items/{id}either apply the documented fields or be removed. Return JSON404for unmatched/api/paths before the SPA fallback.
Q-008 · Dead code and unused wiring · Low
- Location:
backend/notifications.go:59-61(isNoRowshas no callers);backend/server.go:38and:96-106(thecarrierNodeclient is built, stored and never used, and it holds the internal secret);backend/db.go:111-140and: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:424and: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
decodeJSONignores are reasonable for optional bodies, butdata.go:620guards 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
decodeJSONignores, or return400on 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.ymland.github/workflows/lint.ymlpaths:filters includebackend/**andfrontend/**but notshared/**, althoughbackend/go.modreplaces the shared module with../shared/backend(docker.ymldoes includeshared/**);.github/workflows/lint.yml:41(node-version: '20') againsttests.yml:64('22'),docker/Dockerfile:4(node:22-alpine) andREADME.md:85(Node.js 22+); no Go lint job (gofmt,go vet,golangci-lint); theformat:checkscript infrontend/package.jsonis not run; Android has no CI (acknowledged in the README). - Description: A breaking change in
shared/backenddoes 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
mainuntested by push-triggered checks. The Docker build compiles it, but does not run its tests. - Recommendation: Add
shared/backend/**andshared/packages/web-ui/**to the Go and frontend workflow paths. Standardize on Node 22. Addgofmt -landgo vetto the Go job, andnpm run format:checkto lint.
Q-011 · Unpinned and inconsistent dependency declarations · Low
- Location:
frontend/package.jsondevDependenciesanddependenciesblocks (21 entries use"latest", includingsvelte,@sveltejs/kit,viteand@tanstack/svelte-query);.github/workflows/tests.yml:70(web-ui installed with--no-package-lock);CollabTableAndroid/app/build.gradle(compose-bom:2024.06.00for the app but2023.10.01forandroidTestImplementation, andretrofitdeclared as bothimplementationandkapt). - 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 cifor web-ui in CI. Align the Compose BOM and remove the redundantkaptRetrofit line.
Q-012 · Release build has minification disabled · Low
- Location:
CollabTableAndroid/app/build.gradle:30(minifyEnabled falsein thereleasebuild type). - Description: The release build ships unshrunk, unobfuscated code, and
proguard-rules.prohas no effect because minification is off. - Impact: Larger APK, and easier reverse engineering of the sync protocol.
- Recommendation: Enable
minifyEnabled trueandshrinkResources truefor 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(mutablebaseUrl,retrofitandcontext);:119-137(initializeandsetBaseUrlrebuild Retrofit);:139-145(theapigetter 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 aStateFlow.
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*.dbor 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
*.dbandbuild-*.txt, and keep only the placeholderbackend/web/.gitkeep.
Verification
-
Go command (all database URL variables unset):
unset DATABASE_URL SHARED_TEST_DATABASE_URL TEST_DATABASE_URL && export PATH=/tmp/medium-pass-gosdk/go/bin:$PATH GOCACHE=/tmp/medium-pass-go-cache GOMODCACHE=/tmp/medium-pass-go-mod && go test ./... && go test -v -run 'Test(ParsePageRequest|InitSchemaCanRunAgainstAnExistingDatabase|CollectionEndpointsPageWithStableCursors|SyncUsesServerChangeTokenInsteadOfClientTimestamp|SyncBoundsAndPagesLargeInitialSync|PerListMembershipScopesDataAndSync|MembershipBackfillPreservesCurrentAPITokenUsers)$' && go vet ./... && gofmt -l . && for bin in postgres psql initdb; do command -v "$bin" || true; donego test ./...passed. All nineTestParsePageRequestcases passed; the six PostgreSQL-backed cases in the focused run skipped becauseTEST_DATABASE_URLis unset.go vet ./...passed andgofmt -l .printed no files.postgres,psqlandinitdbwere not found. -
Frontend commands:
unset DATABASE_URL && npm test(9 passed);unset DATABASE_URL && npm run check(0 errors, 0 warnings);unset DATABASE_URL && npm run lint(passed);unset DATABASE_URL && npm run build(passed after adding the local design-tokens dependency and enablingresolve.preserveSymlinks; the build reports one Svelte warning in sharedlayout.svelte.js:44);unset DATABASE_URL && npx prettier --check src/lib/api.js src/lib/api.test.js src/lib/features/layout/AppShell.svelteandunset DATABASE_URL && npx prettier --check --end-of-line crlf vite.config.js(both passed). -
Build dependency wiring:
unset DATABASE_URL && npm install --save '@gabriel20xx/design-tokens@file:../shared/packages/design-tokens' --offlineadded the local package tofrontend/package.jsonand the lockfile. The Vite build initially exposed the local shared-package symlink resolution issue;resolve.preserveSymlinksfixed it. -
unset DATABASE_URL && npm run format:checkfailed on four untouched files (src/app.css,src/lib/components/ui/dropdown-menu/content.svelte,src/lib/features/layout/SettingsDialog.svelte,src/routes/+layout.svelte) andvite.config.js, whose original CRLF line endings were preserved to keep the change limited. -
Android JVM tests were not run: Java and Gradle executables and a Unix
gradlewwrapper are unavailable. The source test exists at the path listed in Q-004. A final redundant Svelte-check rerun was stopped after the process remained in uninterruptible I/O for several minutes; an earliernpm run checkcompleted successfully before the Vite-only symlink setting.
Notes
- No live AuthGuard instance or browser session was available, and no load benchmark was run. Performance estimates still need realistic data and multiple devices.
- Checked and clean: no
{@html},innerHTMLorevalin the dashboard; error wrapping inbackend/db.goand 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 inbackend/orfrontend/src/. map[string]anyis used for several ad hoc response bodies (backend/web.go:77-89,backend/data.go:464and: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:269setsInsecureSkipVerify(which disables WebSocket origin checks) when the allowed origin is*, and the package is not imported by CollabTable.