- **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.
- **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 of `shared/`. The tracked SQLite files were inspected read-only from a copy. Verification commands and results are below.
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.
- **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.
- **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.
- **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.
- **Status:** Fixed 2026-10-19 — REST and sync now share `cascadeDeleteList`, `cascadeDeleteField` and `cascadeDeleteItem`, 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.
- **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.
- **Status:** Fixed 2026-10-19 — `handleSync` is now a thin adapter over `applySyncRequest` and the per-table `applyLists`, `applyFields`, `applyItems` and `applyValues` helpers. The cascades (`cascadeDeleteList`, `cascadeDeleteField`, `cascadeDeleteItem`), `fieldDefaults` and `upsertValue` are 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 plain `INSERT` rejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go.
- **Location:** `backend/db_test.go` and `.github/workflows/tests.yml` (database-backed tests and a PostgreSQL service); `frontend/src/lib/api.test.js` and the `node:test` suite; `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 `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.
- **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/data` and tokens; frontend tests cover list helpers and credential proof forwarding; and `SyncPageProgressTest.kt` covers the Android page loop. The PostgreSQL tests skip locally because `TEST_DATABASE_URL` is 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.
- **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.
- **Status:** Fixed 2026-10-19 — README and backend README now mark `SECRET` as required unless `AUTH_DISABLED=true`, add it to the Quick Start, correct the `COOKIE_SECURE` description, and document `ALLOWED_ORIGINS`; the Vite dev proxy now forwards `/api`. Files: README.md, backend/README.md, frontend/vite.config.js.
- **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.
- **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 with `nextSyncToken`; 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 without `lastSyncToken` now 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 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`.
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; done
```
`go test ./...` passed. All nine `TestParsePageRequest` cases passed; the six PostgreSQL-backed cases in the focused run skipped because `TEST_DATABASE_URL` is unset. `go vet ./...` passed and `gofmt -l .` printed no files. `postgres`, `psql` and `initdb` were 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 enabling `resolve.preserveSymlinks`; the build reports one Svelte warning in shared `layout.svelte.js:44`); `unset DATABASE_URL && npx prettier --check src/lib/api.js src/lib/api.test.js src/lib/features/layout/AppShell.svelte` and `unset 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' --offline` added the local package to `frontend/package.json` and the lockfile. The Vite build initially exposed the local shared-package symlink resolution issue; `resolve.preserveSymlinks` fixed it.
- `unset DATABASE_URL && npm run format:check` failed 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`) and `vite.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 `gradlew` wrapper 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 earlier `npm run check` completed successfully before the Vite-only symlink setting.
- 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}`, `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.