docs(docs): V1-1.4 animals and relations as built, DEV procedure to M3

Contract §8.3 (differences, relation states, caps, lock order across M2 and
M3, concurrency results, migration states, mutations, residuals), helpers
and derived values; SUPABASE.md §3.3 procedure from DEV's current state to
M3 (not run) and §3.5; TEST_STRATEGY, plan note, backend table, CLAUDE.md.
This commit is contained in:
bchanot committed 2026-10-26 01:06:24 +01:00
1 parent d7845b7339
commit bc6a7ddb6f
6 files changed
+183 -46

No files matched your search

+7 -6
View File
@@ -45,14 +45,15 @@ importer, curation, migration map, review files, seed SQL, upload tool) into the
(feature `curation`); R5.6 switched the sheet fingerprint to `sha256-rfc8785-validated-v1`;
R5.7 deleted `packages/anatomy` and `packages/domain` (`RUST.md` §11.23, test ledger
`crates/core/tests/curation/LEDGER.tsv`).
MVP species: equine only. Open-source MIT.
MVP species: equine only for anatomical sheets (V1-1.4 records ten species of animals; no sheet beyond the equine draft). Open-source MIT.
Product roadmap (owner, 2026-10-25): P0 docs, then V1-1 clients and animals, V1-2 sheets from Supabase,
V1-3 cloud bilans, V1-4 stored PDF and sharing, V1-5 mobile and accessibility pass
(`docs/development/IMPLEMENTATION_PLAN.md` §0; V1-1 contract `docs/development/V1-1_OWNERS_ANIMALS.md`:
business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; on
`feature/v1-1-clients-animals` V1-1.1 and V1-1.2 (validated) and V1-1.3 are built: migrations `20261025100000_workspaces.sql` and
`20261025110000_clients.sql`, tested on PGlite and the isolated stack `pnpm db:sandbox`, not applied to Supabase DEV; V1-1.3 the
native modal dialog (D13) and the Playwright + axe suites (D14, `docs/development/BROWSER_TESTS.md`)).
`feature/v1-1-clients-animals` V1-1.1 to V1-1.3 (validated) and V1-1.4 are built: migrations `20261025100000_workspaces.sql`,
`20261025110000_clients.sql` and `20261026100000_animals_relations.sql` (contract §8.3), tested on PGlite and the isolated stack
`pnpm db:sandbox`, not applied to Supabase DEV; V1-1.3 the native modal dialog (D13) and the Playwright + axe suites
(D14, `docs/development/BROWSER_TESTS.md`); no client or animal screen yet).
---
@@ -125,7 +126,7 @@ pnpm db:reset # replay from zero
pnpm db:test # pgTAP on the real stack
pnpm db:types # regenerate packages/supabase/src/database.types.ts
pnpm db:types:check # CI diff
pnpm db:sandbox up fresh|up upgrade <version>|test-db|types [--check]|test|e2e-shell|down # throwaway stack (SUPABASE.md §5.1): migrations tested without touching DEV
pnpm db:sandbox up fresh|up upgrade <version> [<then>]|test-db|types [--check]|test|e2e-shell|down # throwaway stack (SUPABASE.md §5.1): migrations tested without touching DEV
# Reference sheet in the app: the dev server bundles the curated draft; a build does not
pnpm build:preview # SHEET_BUNDLE=draft build (manual validation, preview deployments)
@@ -286,7 +287,7 @@ faunosteo/
│ └─ tests/{client,anatomical-sheets}.test.ts, tests/db/ ← PGlite harness, shim, pgTAP runner, schema↔types test
├─ supabase/
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs), workspaces (V1-1.1: personal workspace per account, access helpers), clients (V1-1.2: client RPCs and search, write budget per workspace)
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs), workspaces (V1-1.1: personal workspace per account, access helpers), clients (V1-1.2: client RPCs and search, write budget per workspace), animals_relations (V1-1.4: species rows, animals, relations with history and voiding, their RPCs and reads)
│ ├─ seed/anatomical-sheets/equine/
│ │ ├─ legacy-sources/ ← the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input, never edited)
│ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL)
+2 -2
View File
@@ -102,8 +102,8 @@ credential, residual paths named in the contract §6.3.
|---|---|---|
| `profiles` | own row; admins via view | own row; roles only through RPC |
| `workspaces`, `workspace_members` (V1-1; cabinets extend them instead of `organizations`) | members, through `caller_workspace_ids()` | none through the API: personal workspace created by trigger; cabinet membership RPCs come with Step 10 |
| `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) |
| `animals` | `can_view_animal` | practitioner with an active relationship or grant |
| `clients`, `animals`, `animal_client_relations` (V1-1, built: M2 and M3) | members of the workspace, through `caller_workspace_ids()` | none through the API: definer RPCs check the write role of the workspace (`writable_workspace_ids()`); relations only between an animal and a client of one workspace (composite keys), voided instead of deleted (`V1-1_OWNERS_ANIMALS.md` §8.2, §8.3) |
| `client_contacts`, `client_consents` (later steps) | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) |
| `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC |
| `report_revisions` | same as parent report | insert via RPC/trigger only |
| `anatomical_sheets` | public metadata through a view; full row for creator, grantee, or follower of a public sheet | creator only; publish via RPC |
+3 -2
View File
@@ -355,8 +355,9 @@ workspace, one personal workspace per practitioner, cabinets later, no global
client record shared between practitioners, no consents, grants, sharing,
files or candidate matching. Contract and technical design:
`V1-1_OWNERS_ANIMALS.md` (business decisions approved; architecture and N1-N9
validated 2026-10-25, BDR-074; V1-1.1 workspaces migration written and tested
in isolation, not applied to DEV). Where the
validated 2026-10-25, BDR-074; the workspaces, clients and animals and
relations migrations (V1-1.1, V1-1.2, V1-1.4) written and tested in
isolation, not applied to DEV). Where the
text above differs (global clients, consents, grants, photo, files, deceased
flow), the contract governs V1-1.
+56 -21
View File
@@ -20,7 +20,8 @@ supabase/
│ ├─ 20261011100000_profiles_professional.sql practice_name, professional_title, siret
│ ├─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md)
│ ├─ 20261025100000_workspaces.sql V1-1.1 (M1): workspaces, workspace_members, personal workspace per account, access helpers, audit correlation cap (§3.3)
│ └─ 20261025110000_clients.sql V1-1.2 (M2): clients, unaccent, client RPCs and search, write budget per workspace, N9 audit filter (§3.4)
│ ├─ 20261025110000_clients.sql V1-1.2 (M2): clients, unaccent, client RPCs and search, write budget per workspace, N9 audit filter (§3.4)
│ └─ 20261026100000_animals_relations.sql V1-1.4 (M3): species rows, animals, relations with history and voiding, their RPCs and reads (§3.5)
├─ seed.sql LOCAL dev accounts + first owner (never run in prod)
├─ seed/anatomical-sheets/equine/ official equine sheet as a DRAFT, generated by `pnpm import:equine`
│ ├─ legacy-sources/ the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input)
@@ -197,13 +198,18 @@ confirmed email, `auth.uid()` only). No API role writes either table; `anon`
and `service_role` hold no privilege on them. From M2 on, record tables use
the same helpers; the app passes its workspace id explicitly.
M1 is written and tested on PGlite and on the isolated stack (§5.1), not
applied to the DEV stack. Applying it there is an owner action, never run by
Claude, never with `db reset`, `db push`, `migration repair` or any
destructive command. Every step below was rehearsed on the isolated stack in
upgrade mode (`pnpm db:sandbox up upgrade 20261025100000`), with the sandbox
container name in place of `supabase_db_faunosteo`. Nothing below prints a
secret: the database password stays in the container's own environment.
M1, M2 and M3 are written and tested on PGlite and on the isolated stack
(§5.1), none is applied to the DEV stack. Applying them there is an owner
action, never run by Claude, never with `db reset`, `db push`, `migration
repair` or any destructive command. The procedure below takes DEV from its
current state (every migration up to `20261013100000` applied, profiles and
fictitious accounts present) to M3 in one run. Every step was rehearsed on the
isolated stack in upgrade mode (`pnpm db:sandbox up upgrade 20261025100000`
for the one-run path, `... 20261025100000 20261025110000` for M1 first, then
M2 and M3), with the sandbox container name in place of
`supabase_db_faunosteo`; on 2026-10-26 the history, dump and count commands
were run again against an M3 sandbox. Nothing below prints a secret: the
database password stays in the container's own environment.
```bash
# 0. Target: the local CLI stack of this project, nothing remote.
@@ -213,12 +219,16 @@ docker ps --filter name=supabase_db_faunosteo --format '{{.Names}} {{.Status}}'
# 1. History: only the V1-1 migrations may be pending.
pnpm supabase migration list --local # every row has local = remote, except the V1-1 ones (remote empty):
# 20261025100000 (M1) on a checkout of 6bf6978-08abe42,
# 20261025100000 and 20261025110000 (M1, M2) from 4adbfcb on
# 20261025100000 (M1), 20261025110000 (M2), 20261026100000 (M3)
# on a checkout from b54c8e5 on (M1 alone: 08abe42; M1 + M2: 2dc04bc)
pnpm db:types:check # the diff must be exactly the objects of those migrations (M1: workspaces,
# workspace_members, workspace_kind, workspace_member_role; M2: clients,
# client_kind, create_client, update_client, set_client_archived,
# search_clients): anything else = drift, STOP
# search_clients; M3: animals, animal_client_relations, animal_sex,
# animal_relation_role, create_animal, update_animal, set_animal_archived,
# create_animal_client_relation, end_/update_/void_animal_client_relation,
# search_animals, list_client_animals, client_archive_preview):
# anything else = drift, STOP
# 2. Existing accounts (the backfill creates one workspace per profile).
docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U postgres -d postgres -t -A \
@@ -228,13 +238,14 @@ docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h
# 3. Backup outside Git (includes auth.users and the migration history), then check it.
mkdir -p ~/faunosteo-backups && chmod 700 ~/faunosteo-backups
docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -h 127.0.0.1 -U postgres -d postgres -Fc' \
> ~/faunosteo-backups/dev-before-m1.dump && chmod 600 ~/faunosteo-backups/dev-before-m1.dump
docker exec -i supabase_db_faunosteo pg_restore --list < ~/faunosteo-backups/dev-before-m1.dump \
> ~/faunosteo-backups/dev-before-v1-1.dump && chmod 600 ~/faunosteo-backups/dev-before-v1-1.dump
docker exec -i supabase_db_faunosteo pg_restore --list < ~/faunosteo-backups/dev-before-v1-1.dump \
| grep -E "TABLE DATA (auth users|public profiles|supabase_migrations schema_migrations)" # three lines expected
# 4. Apply without reset (M1's backfill runs inside the migration). `migration up` applies every
# pending migration of the checkout, in order: to apply M1 alone, run it from a checkout of 08abe42.
pnpm supabase migration up --local # "Applying migration 20261025100000_workspaces.sql" (then ..._clients.sql)
# pending migration of the checkout, in order (a shorter path: run it from the checkouts named in step 1).
pnpm supabase migration up --local # "Applying migration 20261025100000_workspaces.sql", then
# ..._clients.sql, then 20261026100000_animals_relations.sql
```
After applying:
@@ -246,9 +257,12 @@ docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h
|| (select count(*) from public.workspaces) || '"'"' workspaces, '"'"'
|| (select count(*) from public.workspace_members) || '"'"' members, '"'"'
|| (select count(*) from public.profiles p where (select count(*) from public.workspaces w
where w.personal_user_id = p.id) <> 1) || '"'"' profiles without exactly one workspace'"'"'"'
# expected: N profiles, N workspaces, N members, 0 profiles without exactly one workspace
pnpm db:test # pgTAP 001-013 (grants, policies, reads); every file runs in
where w.personal_user_id = p.id) <> 1) || '"'"' profiles without exactly one workspace, '"'"'
|| (select count(*) from public.species where active) || '"'"' active species, '"'"'
|| (select count(*) from public.animals) || '"'"' animals'"'"'"'
# expected: N profiles, N workspaces, N members, 0 profiles without exactly one workspace,
# 10 active species, 0 animals
pnpm db:test # pgTAP 001-014 (grants, policies, reads); every file runs in
# begin ... rollback: rows unchanged (checked on the sandbox)
pnpm db:types:check # no diff
pnpm e2e:avatar # avatar flow and worker on the DEV stack (fictitious seed accounts)
@@ -256,13 +270,14 @@ pnpm e2e:avatar # avatar flow and worker on the DE
Stop and report instead of continuing when: `migration list` shows another
pending migration or a remote-only one; `db:types:check` before step 4 shows
anything beyond the M1 objects; the dump check misses a line; `migration up`
anything beyond the objects listed in step 1; the dump check misses a line; `migration up`
applies anything else than the expected V1-1 migrations; any count after it differs from
the expectation. The backup restores into a scratch database (rehearsed:
every row back; `pg_restore --no-owner` prints privilege errors on
Supabase-managed objects, which do not affect the data). Storage file bytes
(avatars) live in the storage container's volume, not in the dump; M1 does not
touch them.
touch them. No down migration exists: going back means restoring the step 3
dump, an owner procedure of its own that is not rehearsed here.
### 3.4 Clients (V1-1.2, migration M2)
@@ -280,6 +295,26 @@ PGlite 0.3.16, loaded by the harness). An account whose workspace holds a
client can no longer be deleted (D9a); in DEV, delete its clients first from
a privileged SQL session, or reset.
### 3.5 Animals and relations (V1-1.4, migration M3)
Contract: `V1-1_OWNERS_ANIMALS.md` §5.2 to §5.4, §8.3, §9, §10. M3 adds the
species rows (`asinine` to `leporine` and `other`; `equine` unchanged; a row
never means a sheet exists), `public.animals` and
`public.animal_client_relations`. The browser reads them through RLS and
writes them only through `create_animal` (with an optional first relation),
`update_animal`, `set_animal_archived`, `create_animal_client_relation`,
`end_animal_client_relation`, `update_animal_client_relation` and
`void_animal_client_relation` (security definer); `search_animals`,
`list_client_animals` and `client_archive_preview` read (invoker, POST), and
`search_clients` now returns `current_animal_count`. A relation joins an
animal and a client of one workspace (composite keys); it is current, ended
(`ended_at`, `ended_on` when known) or voided (entered by mistake, kept,
frozen, shown nowhere); it is never deleted. New refusal codes:
`duplicate_relation`, `already_ended`. Writes share the workspace budget of
M2. An account whose workspace holds an animal can no longer be deleted
either (D9a): in DEV, delete its relations, animals and clients first from a
privileged SQL session, in that order.
## 4. Writing a migration
1. `pnpm supabase migration new <name>` creates `supabase/migrations/<timestamp>_<name>.sql`.
@@ -341,7 +376,7 @@ Docker.
| Command | What it does |
|---|---|
| `pnpm db:sandbox up fresh` | every migration through `supabase migration up --db-url`, then the seeds of `config.toml` (as `db reset`) |
| `pnpm db:sandbox up upgrade <version>` | the migrations before `<version>`, the seeds, two GoTrue accounts (confirmed, unconfirmed), then `migration up`: the path a DEV database takes |
| `pnpm db:sandbox up upgrade <version> [<then>]` | the migrations before `<version>`, the seeds, two GoTrue accounts (confirmed, unconfirmed), then `migration up`: the path a DEV database takes; with `<then>`, the migrations before `<then>` first (the workspaces count is printed), then the rest |
| `pnpm db:sandbox test-db` | `supabase test db --db-url`: the pgTAP files on the real image (rows unchanged afterwards) |
| `pnpm db:sandbox types [--check]` | `supabase gen types --db-url ... --schema public` through Prettier, written or diffed with the committed file |
| `pnpm db:sandbox test` | `packages/supabase/tests/sandbox/*.sandbox.ts`: real GoTrue and PostgREST sessions, concurrent SQL sessions |
+8
View File
@@ -26,6 +26,14 @@ V1-1.3 (2026-10-25): the first real-browser suites (D14,
Chromium, desktop and 375 × 667, under `apps/app/e2e`. `pnpm e2e:ui` (no
backend) 26 cases, `pnpm e2e:shell` (isolated stack) 6 cases; vitest app 458
(Dialog and avatar confirmation wiring added).
V1-1.4 (2026-10-26): supabase vitest 59 (animal and relation parity cases
added), 14 pgTAP files (`014_animals_relations.sql`, 258 checks; 919 in all),
the sandbox suites 46 real-stack checks (`animals.sandbox.ts` 18: HTTP per
role, no lock outside the workspace, replays, relation races, caps and the
shared budget under concurrency, D9a through GoTrue admin, read timings on
20 000 animals), run in four migration states; 14 deliberate faults of M3
caught (`V1-1_OWNERS_ANIMALS.md` §8.3). The axe exceptions match rule,
selector, markup and route.
## 1. Layers
+107 -15
View File
@@ -8,10 +8,12 @@ et autorisation de V1-1.1 Workspaces », BDR-074, §13.2), with the precisions
written into §5.3, §9 and §10. The interface choices of §13.3 stay proposals
until their UI steps. V1-1.1 was validated by the owner on 2026-10-25 (brief
« Validation V1-1.1 et autorisation V1-1.2 Données clients », BDR-075), which
authorised V1-1.2. Migrations M1 (§8.1) and M2 (§8.2) are written and tested
on the isolated stack (`pnpm db:sandbox`, SUPABASE.md §5.1); neither is
applied to Supabase DEV (owner procedure: SUPABASE.md §3.3). Nothing of
V1-1.3 to V1-1.6 exists.
authorised V1-1.2. V1-1.2 and V1-1.3 were validated on 2026-10-25 and
2026-10-26 (BDR-076; brief « Validation V1-1.3 et autorisation V1-1.4
Animaux et relations », BDR-077), which authorised V1-1.4. Migrations M1
(§8.1), M2 (§8.2) and M3 (§8.3) are written and tested on the isolated stack
(`pnpm db:sandbox`, SUPABASE.md §5.1); none is applied to Supabase DEV (owner
procedure: SUPABASE.md §3.3). Nothing of V1-1.5 and V1-1.6 exists.
Branch: `feature/v1-1-clients-animals`. Roadmap position:
`IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays
the permission frame of Step 10. The file name keeps "OWNERS" so the documents
@@ -519,7 +521,7 @@ term travels in a POST body), audit rows, application logs or error messages
---
## 8. SQL schema (M1 written, M2 and M3 proposed)
## 8. SQL schema (M1, M2 and M3 written)
Three forward-only migrations, one per data step, each with its pgTAP files,
the regenerated `database.types.ts` and the census updates in the same branch
@@ -530,7 +532,7 @@ differences from the sketch below: §8.1.
|---|---|---|
| M1 `20261025100000_workspaces.sql` (written, V1-1.1) | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS |
| M2 `20261025110000_clients.sql` (written, V1-1.2) | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS |
| M3 `<ts>_animals_relations.sql` | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS |
| M3 `20261026100000_animals_relations.sql` (written, V1-1.4) | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS |
Why the correlation header in M1: `private.log_event` copies that request
header verbatim today (foundation migration), the app never sends it, and
@@ -789,6 +791,93 @@ INSERT ON public.clients TO authenticated; ». It names the table, the role
and the privilege, never a value, and the app never sends such a request.
The RPC refusals carry no hint (checked on both engines).
### 8.3 M3 as built (V1-1.4, 2026-10-26)
`supabase/migrations/20261026100000_animals_relations.sql`, tested by
`supabase/tests/014_animals_relations.sql` (258 checks), the census of
`001_schema.sql` and `013_clients.sql`, the parity test (animal text fields,
year and date floors) and the sandbox suite
`packages/supabase/tests/sandbox/animals.sandbox.ts` (18 tests). Differences
from the sketch and from §9:
| Point | Sketch or contract | As built | Why |
|---|---|---|---|
| Replay with other content | clients only (§8.2) | `create_request_digest` on animals and relations too, never granted to an API role; a divergent replay is `request_conflict` | the same rule for every create |
| Initial relation of `create_animal` | "in the same transaction" | the relation reuses the animal's `create_request_id` (unique per table), so a replay answers the same `relation_id`; it counts as two audited writes in the budget (two audit rows) | idempotence of the two-row create; the budget counts audited writes (§10) |
| Species filter of `search_animals` | parameter `species_id` | `species_filter` | PostgreSQL refuses a parameter named like the `species_id` output column |
| Cursor of `list_client_animals` | `after_sort` | each row returns `sort_key`: `0` (current) or `1` (former) followed by the animal's `name_key`; keyset on `(sort_key, relation_id)` | one text cursor covers both groups |
| Output of `list_client_animals` | "relation and animal columns" | `relation_id`, `relation_role`, `started_on`, `ended_on`, `is_current`, `relation_revision`, `animal_id`, `animal_name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `animal_archived_at`, `sort_key` | what the client page needs to show and to end or void a relation |
| `client_archive_preview` | `{count, animals}` | `{count, animals: [{id, name}]}`, the first 10 in name order | |
| Replay of a relation create | archived, then revision, then rules | the replay is answered right after the locks, before `archived`: a retry of a committed create returns it even if the animal or the client was archived since | idempotence |
| Dates and years | parsed in each body | `private.parse_record_date`, `private.parse_birth_year`, and the bound `private.utc_tomorrow(timestamptz)`, pure, so pgTAP pins « 1 January accepted on 31 December UTC » without the clock | one rule, testable |
| Opening of the relation writes | per RPC | `private.lock_relation_for_write`: authorise, lock the animal then the relation, refuse `archived`, `conflict`, then a voided row (`invalid_input`) | the same order in the three RPCs |
| `search_clients` | "recreated with the column" | dropped and created again with the same parameters, rules and privileges, plus `current_animal_count` | a return type change needs a drop |
| Access layer `animals.ts`, `relations.ts` | V1-1.4 (TODO) | moved to the UI steps | first consumer, as `clients.ts` at V1-1.2 |
Relation states. `ended_at` tells an ended relation from a current one, so a
relation whose end is recorded without a known date is unambiguous; the
contract needed no change (owner brief §7).
| State | `ended_at` | `ended_on` | `voided_at` | Shown | Current index, cap of 20 | Totals of 200 and 100 000 |
|---|---|---|---|---|---|---|
| current | null | null | null | current | yes | yes |
| ended, date known | set | the date | null | former, with its date | no | yes |
| ended, date unknown | set | null | null | former, no end date | no | yes |
| voided (entered by mistake, current or ended) | as entered | as entered | set | nowhere | no | yes |
Caps: a current relation (`ended_at` and `voided_at` null) counts against
20 per animal; every row, ended and voided included, counts against 200 per
animal and 100 000 per workspace, so a create-and-void loop is bounded. The
200 and 20 are counted under the animal row lock, the 100 000 and the 20 000
animals under the workspace row lock.
Lock order as built, M2 included. Every write RPC takes the budget row last
and the others in the order workspace, animal, relation, client; none takes
two of them the other way round, so no wait cycle can form:
| RPC | Locks, in order |
|---|---|
| `create_client` | workspace (no key update), budget |
| `update_client`, `set_client_archived` | client (update), budget |
| `create_animal` | workspace (no key update), client (share, with a relation), budget (once, twice with a relation) |
| `update_animal`, `set_animal_archived` | animal (update), budget |
| `create_animal_client_relation` | workspace (no key update), animal (update), client (share), budget |
| `end_`, `update_`, `void_animal_client_relation` | animal (update), relation (update), budget |
The relation RPCs first read the animal's (or the relation's) workspace among
the caller's writable ones without a lock, so a caller outside the workspace
takes none: with A's client, animal and relation rows held for 2 s, B's four
refusals answered in 15 ms.
Results on the isolated stack: 8 identical `create_animal` calls with a
relation gave one animal, one relation and two counted writes; 10 identical
relations, one row and nine `duplicate_relation`; end and void racing on one
revision (6 rounds of 3 calls), exactly one applied each time; 6 links at 18
current relations, 2 passed; a relation create racing the archive of its
client or of its animal (10 rounds each), created before or refused
`archived`; at 990 writes, 30 mixed client, animal and relation writes, exactly
10 passed; 5 `create_animal` at 19 998 animals and 5 links at 99 998
relations, 2 each (49 ms for the five links); 96 mixed M2 and M3 writes in one
workspace, no deadlock (109 ms). Reads over 20 000 animals, 20 000 relations
and 1 000 clients (24 POST calls): median 7.9 ms, p95 11.8 ms.
Migration states, each from an empty sandbox: from zero; a pre-M1 base
(seeds, GoTrue accounts) then M1 to M3; the same base, M1 (backfill of five
workspaces), then M2 and M3 (`pnpm db:sandbox up upgrade 20261025100000
20261025110000`); an M1 and M2 base then M3. In each: the 14 pgTAP files
green (919 checks), the generated types identical to the committed file, the
sandbox suites 46/46. Fourteen deliberate faults of M3 were each caught; two
only after the tests were strengthened (a client whose only link was voided
while current; B linking its own animal to a client of A, which made B wait
on A's lock).
Not built: reopening an ended relation (§5.3: void it and create it again).
Residual: a privileged SQL writer (the table owner) can still change a
relation's `animal_id`, `client_id` or `relation_role` inside one workspace,
and move an animal without relations to another workspace (the evolution path
of §4); the RPCs never do, and the composite keys refuse any row across
workspaces whatever writes it.
---
## 9. Policies, helpers and RPCs
@@ -806,8 +895,11 @@ The RPC refusals carry no hint (checked on both engines).
| `private.create_personal_workspace()` | trigger | after insert on `profiles`: calls `ensure_personal_workspace(new.id)` | none |
| `private.backfill_personal_workspaces()` | `integer` | same for every profile without a personal workspace; idempotent | none |
| `private.check_personal_workspace()` | constraint trigger | deferred to commit: a personal workspace has exactly its account as `holder` (M1, §8.1) | none |
| `private.utc_tomorrow(p_now timestamptz)` | `date` | the latest date a record may carry when written at `p_now`: tomorrow's UTC date (M3, §8.3) | none |
| `private.parse_record_date(p_value text)`, `private.parse_birth_year(p_value text)` | `date`, `smallint` | `YYYY-MM-DD` or four digits, not after `utc_tomorrow(now())` (its year), else `invalid_input` without the value; null stays null (M3) | none |
| `private.lock_relation_for_write(p_relation_id uuid, p_expected_revision integer)` | relation row | authorises and locks animal then relation; `not_found`, `archived`, `conflict`, voided `invalid_input` (M3) | none |
All are `security definer` (except `fold_text` and `is_clean_text`, pure SQL functions),
All are `security definer` (except `fold_text`, `is_clean_text`, `utc_tomorrow` and the two parsers, which read no table),
`set search_path = ''`, `revoke all ... from public, anon, authenticated,
service_role` then the grants of the table, and listed in the census of
`001_schema.sql`. The write RPCs do not call `private.require_actor()`: its
@@ -921,7 +1013,7 @@ with POST, so terms and cursors stay out of URLs and access logs.
| RPC | Parameters | Returns (one row per record) | Rules |
|---|---|---|---|
| `search_clients` | `workspace_id`, `query`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `kind`, `display_name`, `city`, `phone`, `email`, `archived_at`, `name_key`; `current_animal_count` added by M3 (§8.2) | see below; also serves the client picker of the relation forms |
| `search_animals` | `workspace_id`, `query`, `species_id`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `archived_at`, `name_key`, `current_owners`, `current_owner_count` | see below; optional species filter |
| `search_animals` | `workspace_id`, `query`, `species_filter` (§8.3), `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `archived_at`, `name_key`, `current_owners`, `current_owner_count` | see below; optional species filter |
| `list_client_animals` | `client_id`, `page_size`, `after_sort`, `after_id` | relation and animal columns | a client's relations with their animals, current first then former, each group by animal `name_key`, then `id`; keyset on that order; 50 by default, 100 at most |
| `client_archive_preview` | `client_id` | `{count, animals}` | active animals for which this client holds the only current `owner` relation: their count and the first 10 by name |
@@ -938,8 +1030,8 @@ Derived values:
| Value | Exact rule |
|---|---|
| `current_animal_count` | `count(distinct animal_id)` over the client's relations with `ended_at is null`, any role, animals not archived |
| `current_owners` | the animal's relations with `relation_role = 'owner'` and `ended_at is null`, archived clients included and flagged, ordered by client `name_key` then `id`, first three as `{client_id, display_name, archived}` |
| `current_animal_count` | `count(distinct animal_id)` over the client's relations with `ended_at is null` and `voided_at is null`, any role, animals not archived |
| `current_owners` | the animal's relations with `relation_role = 'owner'`, `ended_at is null` and `voided_at is null`, archived clients included and flagged, ordered by client `name_key` then `id`, first three as `{client_id, display_name, archived}` |
| `current_owner_count` | the count of those relations |
| « only current owner » (archive preview) | the animal is active, this client has a current `owner` relation, and no other client, archived or not, has one |
@@ -1176,7 +1268,7 @@ validated mockups unchanged).
### 12.1 SQL (pgTAP, on PGlite and on the real stack)
Files: `012_workspaces.sql`, `013_clients.sql`,
`014_animals_relations.sql`; updates to `001_schema.sql` (tables, RLS,
`014_animals_relations.sql` (258 checks); updates to `001_schema.sql` (tables, RLS,
privileges, helper census) and to `packages/supabase/tests/db/schema-types.test.ts`;
the PGlite harness loads `unaccent`.
@@ -1351,10 +1443,10 @@ validates after V1-1.1 and after the first UI step; nothing merges into
| Step | Content |
|---|---|
| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), awaiting the owner's checkpoint; not applied to DEV |
| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, sandbox suite. Written and tested on the isolated stack (§8.2), awaiting the owner's checkpoint; not applied to DEV |
| V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13). Built (§11.6), awaiting the owner's checkpoint |
| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof |
| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), validated 2026-10-25; not applied to DEV |
| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, sandbox suite. Written and tested on the isolated stack (§8.2), validated 2026-10-25; not applied to DEV |
| V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13). Built (§11.6), validated 2026-10-26 |
| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof. Written and tested on the isolated stack (§8.3), awaiting the owner's checkpoint; not applied to DEV |
| V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry |
| V1-1.6 | Animals and relations UI, navigation (D11), dashboard tiles (D12), documents, Definition of Done |