← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / xhigh / xhigh effort preferred over openai / gpt-6-astra / high / high effort · close win.

Primary judge: Sol 6.1, requested Low. Effective provider effort and internal attempts were not verified. A close win is still a scored preference; it does not establish a material defect.

Reviewed public evidence

Task goal

Assess a safe, backward-compatible rollout and rollback for the current [REDACTED: private project name] tenant schema represented by these migrations and SQL tests. Treat the schema as already deployed with existing tenant data while API services and workers may run mixed versions during rollout. Ground every claim in the supplied files and cite the relevant definitions or assertions. Identify concrete ordering, compatibility, lock/backfill, integrity, tenant-isolation, and rollback risks; separate proven behavior from assumptions about application code not included here. Give a phased expand/migrate/verify/contract plan, explicit rollback boundaries after writes, and measurable pre/post-deployment checks using the existing test contracts. Do not invent application APIs, claim tests were run, or edit code.

openai / gpt-6.1-sol / xhigh / xhigh effort answer

## Conclusion

**Do not replay these migrations or treat rollback as “run them backward.”** For an already-populated deployment, the safe approach is to preserve existing data and interfaces, establish an old/new service compatibility matrix, verify effective tenant isolation, and defer privilege or policy contraction until all incompatible consumers are retired.

This is a direct, independent review of the supplied snapshot. **No tests were run and no code was changed.** Confidence is high in the SQL definitions and test-contract discrepancies; deployed behavior remains conditional on live ownership, grants, view definitions, and application code.

### Citation key

- **M02:** `supabase/migrations/00002_create_schema_and_tenant.sql`
- **M03:** `supabase/migrations/00003_create_core_tables.sql`
- **M08:** `supabase/migrations/00008_enable_rls_and_policies.sql`
- **M15:** `supabase/migrations/00015_hardening.sql`
- **IT:** `supabase/test-integration.sql`
- **RT:** `supabase/test-rls.sql`

## 1. Findings and rollout implications

### Ordering and replay safety

- **These are creation scripts, not convergence migrations.** `CREATE TABLE IF NOT EXISTS` does not reconcile an existing table’s columns or constraints. M02 also creates indexes without `IF NOT EXISTS`; M08 creates several named policies without first dropping them. Replaying can therefore fail or leave drift undetected. [M02:12–30,51–53; M03:6–56; M08:71–91]
- **Replaying M08 can overwrite later policy changes.** Its helper drops the standard policies and replaces them with member-only policies, including on the back-office tables. This would remove Directus allowances if those had subsequently been incorporated into the same policies. [M08:32–46,56–62]
- **Historical dependencies matter:** tenant foundations precede core tables; all named relations must exist before M08 applies policies; the five public API views must exist before M15 grants access. Their definitions, and several named tables, are outside this packet. [M02:12–30; M03:8,29–30,46–47; M08:52–66; M15:16–22]
- **Atomicity differs.** M15 explicitly wraps its changes in a transaction. M02, M03, and M08 do not show whole-file transaction boundaries; migration-runner behavior is unknown. M08’s initial `DO` block enables RLS before subsequent policy statements, so an autocommit execution that later fails could leave a partially configured deployment. [M15:1–24; M08:6–18,52–91]

**Recommendation:** compare migration history and actual catalogs with these definitions; issue targeted forward migrations rather than rerunning the historical files.

### Mixed-version compatibility and privileges

- **M15 is an access-contract change, even though it changes no columns.** It revokes `authenticated` access to app tables, sequences, and functions, then grants SELECT on only five public API views. An old service using direct app-table access or an app function can fail once its effective privileges disappear. [M15:4–22]
- **The SQL tests still exercise the older surface:** app tables, app views, and `app.compute_deltas()`. They do not verify the five granted public API views. Consequently, these tests alone cannot certify post-hardening API compatibility. [IT:75–150,315–323; RT:170–175,237–241; M15:16–22]
- **Revoking a grant from `authenticated` does not prove effective denial.** PostgreSQL privileges can still come through `PUBLIC`, inherited roles, or ownership. M15 does not revoke `PUBLIC` function execution, inherited access, or pre-existing write grants on the public views. Its “read-only” comment is therefore an intent, not proof of effective read-only access. [M15:3–22]
- **Default privileges are not universal.** The statements shown affect defaults associated with the executing object-creator role; they do not establish defaults for every possible future creator. Nor does M08 automatically enable RLS on tables created later. [M15:11–13; M08:10–17]
- **Search-path changes can differ across pooled connections.** M02 changes the database default to `app, public, extensions`; it does not establish an identical path for already-connected sessions or role-specific overrides. Mixed-version code using unqualified names needs explicit verification. [M02:8–9]

Preserve the actual existing access contract during expansion. Do not “restore compatibility” with blanket grants; identify and, where authorized, retain only the privileges each old consumer genuinely needs.

### Tenant integrity is weaker than row-level membership isolation

**The schema permits cross-tenant parent/child links.**

- A survey independently references a tenant and an asset UUID; no constraint requires the asset’s tenant to match the survey’s tenant. [M03:27–38]
- An observation independently references a tenant and survey UUID; again, tenant equality is not enforced. [M03:44–56]
- RLS checks the child row’s `tenant_id`, not the referenced parent’s tenant. [M08:38–45]

Thus, a survey owned by tenant B can reference tenant A’s asset while satisfying the shown foreign keys. This does **not** by itself prove parent data is readable, but it creates integrity and isolation risks. Because the references cascade, deleting the tenant-A asset can also delete the tenant-B survey and its observations through referential actions. [M03:30,47]

Additional implications:

- Asset external codes are unique **within** a tenant, not globally. Worker lookup by external code alone would be unsafe, but no worker implementation is supplied. Also, `asset.asset_id` is text while `survey.asset_id` is a UUID reference; migration/backfill logic must preserve that distinction. [M03:7–9,20,30]
- The policy permits members of both tenants to change a row’s tenant from one to the other, subject to other constraints: `USING` checks the old row and `WITH CHECK` checks the new row. It does not enforce an “active tenant” selected by the application. [M08:44–45; M02:42–46]

**Deployment gate:** measure both parent/child mismatch counts and require zero before claiming tenant-consistent integrity. Application validation alone is not proven by this packet.

### Membership roles and provisioning

- The schema labels viewers read-only, but `is_member()` ignores `role`, and the standard modification policy admits every member for all operations. With sufficient SQL privileges, a viewer passes the same policy as an admin. ACLs may still prevent writes, but the RLS layer does not implement the documented role distinction. [M02:27,33,36–47; M08:42–45]
- `tenant_member.user_id` has only a comment suggesting an auth-user reference; no auth-user foreign key is declared. Auth-user deletion cleanup is therefore not established here. [M02:24–30]
- Tenant and membership policies shown are SELECT-only. Ordinary RLS-controlled provisioning writes need some additional authorized path, which is not supplied. [M08:79–91]

Do not combine a viewer-write restriction or provisioning redesign with an otherwise backward-compatible rollout without explicitly testing those behavioral changes.

### Security-definer and audit-policy risks

- Both helpers are `SECURITY DEFINER`, without a fixed function `search_path`. `is_member()` explicitly qualifies its table and auth function, which limits—but does not eliminate—the need to examine its execution environment. [M02:36–47; M08:21–25]
- `apply_member_policies()` interpolates a caller-controlled relation string with `%s` into privileged DDL rather than safely identifying an allowlisted relation. If untrusted roles can execute it, this is a serious privileged-DDL risk. Actual exploitability depends on effective EXECUTE permission and the function owner’s authority; neither is established. M15’s revocation from `authenticated` alone does not settle this because `PUBLIC` grants may remain. [M08:21–46; M15:9]
- Audit SELECT permits either the event’s user **or any tenant member**, despite the “own events” comment. INSERT checks only `user_id = auth.uid()`, not tenant membership. Subject to unseen table constraints and grants, that can permit a user to submit an event against a foreign tenant. [M08:68–77]

Restrict the policy-management helper to migration administration, verify helper ownership and effective execution permissions, and treat any audit-policy tightening as a separate compatibility change.

### Lock, backfill, and retry risks

- M02’s ordinary index creation is not concurrent; on existing tables it can block writes and requires a scan. M08 performs relation-locking RLS and policy DDL across many tables. Long-running transactions can delay that DDL and extend disruption. [M02:51–53; M08:6–18,32–46]
- **No data backfill appears in the supplied migrations.** M15 changes ACLs, not stored tenant data. Do not attribute a table rewrite or backfill to that file. [M15:1–24]
- `updated_at` has an insertion default, but no automatic update mechanism is shown. It is not a proven watermark for backfill catch-up or rollback journaling. [M02:16–17; M03:18–19,36–37]
- Survey and observation fixtures are not demonstrably retry-idempotent. Their fresh UUID defaults have no shown business-key uniqueness constraint, so `ON CONFLICT DO NOTHING` can insert another row on each execution. Multiple surveys on the same date may also be legitimate; deduplication rules cannot be inferred. [M03:27–56; RT:82–102]

## 2. Phased expand / migrate / verify / contract plan

### Phase 0 — Establish the deployed baseline

Before changing anything:

1. Record actual relation definitions, validated constraints, indexes, policies, function owners/ACLs, view definitions, RLS flags, default privileges, and role membership.
2. Build a compatibility matrix for **old and new API services, workers, and Directus**, using their real database identities and actual read/write operations. The tests show expected ingestion and Directus workflows, but not implementation compatibility. [IT:80–150,162–287]
3. Record per-tenant row counts and both cross-tenant relationship mismatch counts; identify dangling membership users.
4. Establish a recoverable backup/PITR checkpoint and rehearse restoration plus reconciliation of subsequent accepted writes.
5. Use an isolated restored environment for mutation-heavy tests. The supplied integration script alters tenant data; its optional cleanup deletes all AMP sections and LOS targets for the selected tenant. That is unsafe as production cleanup with existing data. [IT:165–171,183–187,205–210,226–238,426–433]

### Phase 1 — Expand without breaking current consumers

- Preserve core column types, UUIDs, tenant-scoped asset codes, current view names, and verified output shapes. [M03:6–56; M15:16–22]
- Do not remove an access path until the compatibility matrix shows no remaining dependent old consumer. If M15 is already effective, preserve that boundary and adapt consumers to the supported surface rather than assuming app-table access remains available.
- Make policy replacements atomic and narrowly scoped. Do not replay M08’s blanket policy helper over already-evolved back-office policies. [M08:32–46,52–66]
- Remove unintended access to privileged management helpers while preserving verified read-helper dependencies. Confirm that the chosen public-view design works with the intended base-table privilege restrictions.

**Important:** blindly making views `security_invoker` is not a complete remedy. Invoker views ordinarily need caller access to their underlying relations, potentially conflicting with M15’s revoked app-table privileges. The actual view definitions must determine the solution.

### Phase 2 — Migrate data and enforce tenant consistency

There is no required historical backfill in these files. If audits find mismatches:

- Identify the authoritative tenant and relationship for each affected record. Do not automatically rewrite child tenants or delete parents.
- Pause or fence affected writers through existing operational controls while repairing those records; no such control mechanism is shown here.
- Repair in bounded, resumable batches keyed by stable UUIDs. Retain before/after values and ownership decisions for rollback.
- To enforce equality, an additive option is composite foreign keys:
  - survey `(tenant_id, asset_id)` → asset `(tenant_id, id)`;
  - observation `(tenant_id, survey_id)` → survey `(tenant_id, id)`.
  
  These require suitable parent uniqueness and must retain intentionally chosen deletion semantics. The need follows directly from the independent references in M03. [M03:8,20,29–30,46–47]
- Where appropriate, build supporting indexes concurrently outside a transaction, check for failed/invalid indexes, then add and validate constraints.

**`NOT VALID` is not a mixed-version bypass:** a newly added foreign key still checks new writes. All active writers must already comply, or the rollout must deliberately accept rejection of noncompliant writes. Validation also scans data and consumes resources; stage and measure it.

### Phase 3 — Verify under real identities and mixed versions

Use the checks below before and after the candidate change, first in the restored environment and then with controlled production checks.

Do not run the unscoped `app.compute_deltas()` call on production merely because it is in the test plan: its implementation and affected tenants are unknown. [IT:139–150]

### Phase 4 — Contract only after the compatibility window

Contract only when:

- No incompatible old API instance or worker remains.
- In-flight and retryable work from old versions has been drained or demonstrated compatible; queue behavior is not supplied.
- Required constraints are validated.
- Public-view isolation, Directus restrictions, and mixed-version workflows pass.
- The rollback retention window and write-reconciliation procedure are approved.

Only then remove obsolete grants/interfaces or tighten role semantics. For ACL contraction, use an exact approved grant manifest, not the assumption that M15 proves all unintended access has disappeared.

## 3. Measurable pre/post-deployment checks

| Check | Required measurement and interpretation | Existing contract |
|---|---|---|
| RLS coverage | Every intended tenant base table has RLS enabled; record owners and `FORCE RLS` status separately. Enabled RLS alone does not prove owner/superuser filtering. | M08:6–18; RT:116–131 |
| Membership isolation | A has pilot membership; B has none. Under real non-bypass identities, A sees authorized pilot records and B sees none. After adding B to the second tenant, each sees only tenants they belong to. | IT:40–64; RT:162–185,191–231 |
| Parent/child integrity | Count surveys where `survey.tenant_id <> asset.tenant_id`, and observations where `observation.tenant_id <> survey.tenant_id`; both must be **0**. Attempted mismatched writes must be rejected once enforcement is installed. | M03:27–56 |
| Effective hardening | For `authenticated`, inherited roles, and `PUBLIC`, inspect schema/table/view/function privileges. Verify intended app-base denial and SELECT-only public-view access, including absence of effective DML grants. | M15:4–22 |
| Public API isolation | Test all five `public.api_*` views with member and outsider identities; compare returned identifiers or aggregates against authorized fixture data. The supplied app-view tests do not cover this surface. | M15:16–22; IT:315–337 |
| Privileged helper exposure | Untrusted roles cannot execute the policy-management helper; owners and search paths are approved. Required read-helper access still works. | M08:21–46; M02:36–47 |
| Ingestion fixture | In the defined golden-data environment: ≥3 assets; ≥2 queued/parsed manifests; ≥2 parse jobs; ≥6 surveys spanning ≥3 assets; ≥15 observations; ≥3 deltas, ≥1 deteriorating, ≥1 severe. Also compare exact fixture identifiers and expected increments so thresholds do not hide duplicate ingestion. | IT:75–150 |
| Directus capabilities | Unit-cost insert/update succeeds and yields `70.00`; LOS, AMP, and unmatched-resolution fixtures meet their expected results. Core access is denied or filtered according to the intended privilege contract. | IT:162–287,363–375 |
| Directus authority | `rolsuper=false`, `rolbypassrls=false`, `rolcanlogin=true`; verify complete policy `USING` **and** `WITH CHECK` semantics, not merely substring presence. | IT:349–390 |
| Operational impact | Set numeric abort thresholds before deployment for lock wait, request permission errors, worker failures, and queue age; monitor against baseline. These are operational additions, not assertions already supplied by the tests. | DDL risk: M02:51–53; M08:6–18; workflow evidence: IT:95–123 |

### Existing test limitations that must be corrected

1. **`SET ROLE postgres` is not a reliable user-RLS test.** Setting a JWT subject does not remove superuser, owner, or bypass privileges. No `FORCE ROW LEVEL SECURITY` is shown. Verify actual role properties and test through genuine non-bypass identities. [IT:54–60,312–337; M08:16; RT:113–114,175–176]
2. **The JWT `SET` statements contain subqueries**, which are not valid PostgreSQL `SET` value syntax. Resolve the UUID first and set it through a supported session-setting mechanism in an isolated test transaction; verify that `auth.uid()` resolves as intended. [IT:56,313,332; M02:45]
3. **Several “simulation” queries never change identity.** Their successful counts establish data existence, not tenant isolation. RT itself acknowledges this distinction and requires actual user testing. [RT:137–176,218–231,276–285]
4. **Permission denial and zero rows are different outcomes.** Post-hardening direct app access can appropriately fail with an ACL error rather than return zero. Neither outcome substitutes for verifying that the supported public views correctly filter outsiders. [M15:7–22; IT:371; RT:173]
5. **“Views inherit RLS” is unproven.** View ownership and security configuration are absent. Owner-executed views can bypass underlying RLS depending on ownership and role properties. [IT:308–341; RT:237–241]
6. **Positive counts require suitable fixtures.** A legitimate empty report is not automatically a security or rollout failure, and minimum counts alone do not prove correct tenant attribution or prevent duplicates. [IT:132–150,325]

## 4. Explicit rollback boundaries after writes

| Boundary | Safe rollback position |
|---|---|
| Candidate transaction fails before commit | Its transactional changes roll back. This is explicit for M15; do not assume whole-file atomicity for the earlier migrations. [M15:1–24] |
| Additive deployment, before incompatible writes | Roll back code while retaining additive schema, provided old versions still accept the data and constraints. Removing expansion objects is usually unnecessary. |
| ACL/policy cutover, with otherwise unchanged compatible data | Restore the **captured** approved ACLs/default privileges or policy definitions if authorized. This reverses access changes, not writes or external effects. Restoring an insecure policy is not a safe default. [M08:32–46; M15:4–22] |
| New tenant-equality enforcement | Old code may now fail if it creates mismatches. Prefer fixing or fencing that writer over dropping the isolation constraint. Removing enforcement would deliberately reopen the proven integrity gap. [M03:29–30,46–47] |
| Data repaired, retagged, or new semantics written | A code rollback alone is insufficient. Use the repair journal and reconcile later writes before reversing values; do not overwrite subsequent legitimate changes. |
| Cascading deletion committed | Regranting privileges or restoring policies cannot recreate deleted rows. Restore/reconstruct from retained data, respecting dependency order and subsequent writes. [M02:25; M03:8,29–30,46–47] |
| Destructive contract or whole-database restore | Old-code rollback may require restoring removed interfaces/data. PITR without replay loses valid post-checkpoint writes; replay idempotence is not proven. External S3 uploads are outside the database transaction. [RT:82–102; IT:80–84,289–302] |

No down migrations, repair journal, or tested post-write replay procedure is supplied. Consequently, **automatic rollback after semantic writes or cascading deletes is not established**.

## 5. Uncertainties, alternatives, and next action

### Important uncertainties

Definitions outside this packet determine:

- Public and app view security, output compatibility, and actual filtering.
- Directus policy extensions and `app.is_directus()` behavior.
- Worker/service roles, tenant validation, retry/idempotency, and queue compatibility.
- `auth.uid()` configuration and `compute_deltas()` scope.
- Live grants, ownership, triggers, migration-runner transactions, and recoverability.

These are uncertainties—not proof that the deployment is broken or that another file is missing.

### Alternatives and likely false positives

- Later policy changes could explain the Directus contract; do not assume member-only M08 policies are still the deployed versions.
- Other grants could explain successful app access after M15, but that success would not prove hardening.
- Public views might safely implement explicit tenant filtering; conversely, a privileged view-owner test might appear successful while bypassing isolation.
- Repeated survey records are not necessarily invalid; the schema declares no business uniqueness suitable for automatic deduplication.

**Next useful action:** produce a read-only live-state and old/new compatibility report, then rehearse the corrected identity tests and rollback-with-write-reconciliation on a restored populated database. Proceed only when that evidence resolves the privilege, view-isolation, Directus-policy, and tenant-equality gates.

MATERIAL_EVIDENCE_CONFLICT: M08:38–45,56–60 defines member-only policies for back-office tables, while IT:377–390 requires those policies to include app.is_directus(); an additional policy change would be needed to reconcile the supplied definitions with that assertion.

openai / gpt-6-astra / high / high effort answer

## Conclusion

**Treat these files as deployed history, not a migration sequence to replay.** A backward-compatible rollout requires additive changes followed by verified application/worker compatibility before tightening access or constraints. The main risks are:

1. `00015` removes direct `authenticated` access that earlier policies and test instructions appear to expect.
2. The core foreign keys allow cross-tenant parent/child relationships.
3. Existing tests do not establish effective tenant isolation under production execution roles.
4. Safe rollback after new writes depends on preserving old-readable data and worker compatibility—not merely reversing DDL.

This was an independent, read-only assessment of the supplied snapshot. No tests were run.

**Citation shorthand:** `M02`, `M03`, `M08`, `M15` denote the four supplied migrations; `IT` denotes `supabase/test-integration.sql`; `RT` denotes `supabase/test-rls.sql`.

## 1. Evidence and concrete risks

### Deployment ordering and mixed-version compatibility

- **The supplied migrations have prerequisites beyond the tenant/core definitions.** `M08` applies policies to numerous additional tables, and `M15` grants access to five existing `public.api_*` views (`M08:51–66`; `M15:15–22`). Their definitions are outside this packet. Confirm their deployed existence, ownership and definitions before any dependent change. These files alone do not establish their compatibility or security.

- **`M15` is an access-contract change, not just additive hardening.** It revokes `authenticated` privileges on all existing `app` tables, sequences and functions, then grants SELECT on five public views (`M15:4–22`). With no other privilege path, old clients accessing `app.asset`, `app.survey`, functions or internal views will receive permission errors. RLS policies cannot supply missing SQL privileges. Whether actual services use those paths is unknown.

- **Mixed versions must agree on more than columns.** Membership roles are restricted to `admin`, `manager`, `viewer`; coverage, direction and grade have explicit checks (`M02:24–29`; `M03:33–35,49`). Changing accepted values or making currently nullable fields mandatory can break old writers. No application or job payload compatibility is demonstrated by the supplied SQL.

- **Database `search_path` is a connection-sensitive dependency.** `M02:9` changes the database default to `app, public, extensions`; existing sessions need not adopt a new default. New and old pooled connections can therefore resolve unqualified names differently during a change. Supplied SQL largely qualifies application objects, but application behavior is unknown.

- **Replay is unsafe.** `CREATE TABLE IF NOT EXISTS` does not reconcile an existing table’s structure. Index creation in `M02:52–53` is unguarded, and named policies in `M08:71–91` are not dropped before creation. The helper also replaces policies on every invocation (`M08:32–45`). Use new forward migrations based on catalog inspection, not rerunning historical files.

### Tenant isolation and integrity

**High-confidence schema gap:** the parent identifiers and tenant identifiers are independently constrained.

- Surveys reference `app.tenant(id)` and `app.asset(id)` separately.
- Observations reference `app.tenant(id)` and `app.survey(id)` separately.
- Neither relationship enforces equal tenant IDs (`M03:27–30,44–47`).

Consequently, a survey can carry tenant A while referencing tenant B’s asset, and an observation can carry tenant A while referencing tenant B’s survey. Standard policies check only the row’s own `tenant_id` (`M08:38–44`), not the parent’s tenant.

**Implications:** incorrect joins, derived data and cascading deletion across tenant boundaries are possible. Actual read leakage depends on the absent view/query definitions; it is not proven here. Foreign-key checks do not substitute for parent visibility checks under RLS.

Other important boundaries:

- **`viewer` is not read-only at the policy layer.** The role comment promises that distinction, but `is_member` checks membership alone, and the modification policy grants `FOR ALL` to any member (`M02:27,33,36–46`; `M08:42–45`). Actual write ability still depends on SQL grants. Removing hardening to restore compatibility could expose member-wide writes if grants are restored indiscriminately.
- **Users belonging to two tenants can satisfy both sides of a tenant-ID update.** The modification policy checks membership in the old and new row tenant, without making tenant ownership immutable (`M08:44`). Whether applications allow such updates is unknown.
- **Membership has no declared auth-user foreign key.** `user_id` is a UUID with a comment mentioning `auth.users`, not a reference constraint (`M02:24–29`). Stale memberships are therefore not excluded by the shown schema.
- **Delete cascades are material rollback boundaries.** Tenant deletion cascades into memberships and core rows; asset deletion cascades into surveys, and survey deletion into observations (`M02:25`; `M03:8,29–30,46–47`). Reversing schema changes cannot recover these deleted rows.
- **Replay deduplication is incomplete in the shown core schema.** Assets have `(tenant_id, asset_id)` uniqueness, but surveys and observations have only generated UUID primary keys for identity (`M03:7,20,28,45`). The test’s `ON CONFLICT DO NOTHING` does not prevent repeated logical survey or observation insertion with fresh IDs (`RT:82–102`). Worker retry idempotency remains an application uncertainty.

### RLS, grants and privileged helpers

- **RLS enablement is a snapshot, not an automatic rule for future tables.** The loop enables RLS on then-existing `app` base tables (`M08:5–18`). Future tables require explicit grants, RLS and policies.
- **Enabled RLS is not evidence of enforcement for every role.** No `FORCE ROW LEVEL SECURITY` appears in the supplied migration. PostgreSQL superusers and `BYPASSRLS` roles bypass RLS; owners ordinarily do too. Inventory actual ownership and execution roles before interpreting test results.
- **The policy installer is a privileged surface.** `app.apply_member_policies(text)` is `SECURITY DEFINER` and interpolates caller-provided text into dynamic SQL with `%s` (`M08:21–45`). If callable by an untrusted role, it can at least replace policies on caller-selected tables within the definer’s authority; unsafe interpolation further enlarges the risk. Actual exploitability depends on deployed ownership and effective EXECUTE privileges.
- **Revoking from `authenticated` does not revoke privileges inherited through `PUBLIC` or other roles.** This is especially important for security-definer functions (`M02:36–47`; `M08:21–47`; `M15:9,13`). Conversely, if the runtime has no other EXECUTE path, revoking `is_member` execution can break policy evaluation for callers relying on it.
- **Default privileges are creator-specific.** `M15:11–13` does not establish defaults for every future object owner and does not revoke `PUBLIC` grants. Verify both current effective privileges and defaults for each deployment role.
- **Public-view safety is unproven.** Granting SELECT on `public.api_*` views does not prove tenant filtering or read-only effective access (`M15:15–22`). View definitions, owner privileges, security options and existing inherited grants must be checked.

There is also a comment/implementation discrepancy in audit access: the comment says users read only their own events, while the policy permits their own **or any event in a tenant they belong to**. Its insert check requires only `user_id = auth.uid()`, not tenant membership (`M08:68–77`). Effective table grants determine whether those paths are reachable.

### Locks, transactions and backfills

- **No data backfill is defined in these migrations.** Any tenant repair or conversion is a new operational step, not an existing tested behavior.
- On populated tables, ordinary index creation and constraint changes can block work or scan substantial data. RLS and policy DDL also require relation locks. `M02:52–53` uses ordinary index creation; `M08:5–18` touches every current `app` base table. Use bounded lock waits, inspect blockers and stage changes on representative data.
- `M15` explicitly groups revocation and grants in one transaction (`M15:1–24`). Failure before commit rolls that transaction back; a long wait should not trigger a duplicate attempt.
- `M08` has no explicit file-wide transaction. Its effective atomicity depends on the migration runner. If statements are separately committed, execution can leave only part of the intended policy set installed (`M08:5–91`).

## 2. What the existing tests establish—and what they do not

These are mostly manual test plans and commented expectations, not self-enforcing assertions.

| Existing contract | Required interpretation |
|---|---|
| Member sees data; outsider sees zero (`IT:40–64`; `RT:134–185`) | `IT` switches to `postgres`; setting a JWT subject does not remove that role’s bypass/ownership privileges. Its `SET … = (SELECT …)` form also requires correction for normal PostgreSQL execution. Resolve IDs first and use a verified non-bypass role with supported claim configuration. |
| RLS enabled and policies present (`RT:116–131`) | Necessary catalog checks, but not proof of effective isolation, correct policy expressions or permitted runtime access. |
| Cross-tenant isolation (`RT:188–231`) | The SQL actually displays both tenants as a privileged role; isolation is described rather than exercised. Test both authenticated identities independently. |
| Views respect RLS (`IT:310–341`; `RT:234–241`) | Owner/bypass execution cannot prove this. The tested `app.v_*` views also differ from the `public.api_*` surface granted in `M15`. Test both where supported. |
| Directus permitted back-office access but blocked from core (`IT:160–287,347–390`) | Role creation/grants and `is_directus()` policy definitions are outside the packet. These are intended contracts, not proven deployed behavior. |
| Ingestion counts and computed deltas (`IT:75–150`) | Useful controlled-fixture acceptance thresholds, but existing tenant data can satisfy them before a rollout. Compare fixture-specific changes and outputs, not only whole-tenant totals. |

A scalar `count(*)` returning **0** is one result row containing zero—not “zero rows.” Distinguish successful filtering from permission errors. After hardening, denied direct base-table access may be intentional, but it does not prove RLS filtering.

**Do not run the scripts unchanged against existing production tenants.** They upsert memberships and business data, create surveys/observations, update costs and unmatched records, and offer tenant-wide cleanup (`RT:29–37,82–102,247–254`; `IT:165–171,183–187,271–275,426–432`). Use dedicated fixtures and ID-scoped cleanup; do not elevate an existing user or delete tenant-wide records to satisfy a test.

## 3. Phased expand / migrate / verify / contract plan

### Phase 0 — Establish the deployed baseline

1. Record schema definitions, owners, effective grants, default privileges, policies, RLS flags, view security properties and role bypass flags. Compare with the cited definitions rather than assuming migration history guarantees structure.
2. Identify the actual database roles and object paths used by every live API/worker version. Verify supported claim propagation and job retry behavior. These are deployment prerequisites because application code is not supplied.
3. Record per-tenant row counts, core integrity violations, job status distributions and representative derived results. Establish a recoverable backup/PITR point and demonstrate recovery in an isolated environment before data-changing work.
4. Run the corrected test contracts against dedicated fixtures using actual execution roles.

**Gate:** no unexplained catalog drift; identified compatibility matrix for all versions that will coexist; verified recovery procedure.

### Phase 1 — Expand

- Preserve existing column names, types and old-readable representations. Introduce any new representation additively, with nullable columns or compatible defaults as appropriate.
- If strengthening parent/tenant integrity, first create suitable unique parent keys such as `(tenant_id, id)`, then add composite foreign keys:
  - survey `(tenant_id, asset_id)` → asset `(tenant_id, id)`;
  - observation `(tenant_id, survey_id)` → survey `(tenant_id, id)`.
- On large tables, use concurrent index creation where applicable and attach suitable constraints in short bounded DDL steps. Concurrent index creation cannot run inside an ordinary transaction block.
- Add foreign keys `NOT VALID` before historical validation where appropriate. **They still check new writes and relevant updates**, so first prove all active writers satisfy them; old invalid rows can also make unrelated workflow updates fail.
- Add explicit security for new objects. Restrict the policy-management helper based on audited callers; retain only the runtime helper access actually required.

**Gate:** all still-live versions read and write successfully through their authorized paths; no unbounded lock wait; no increase in permission or integrity failures.

### Phase 2 — Migrate

- Repair cross-tenant relationships only after determining authoritative ownership. Do not blindly copy tenant IDs from parents: that can move data between security domains.
- Backfill in bounded, resumable batches using stable IDs, checkpoints and before-images or a repair ledger. Make writes conditional so they do not overwrite newer concurrent edits.
- Reconcile concurrent writes before final validation. If correctness cannot be maintained while old workers write, drain or pause the affected workflow.
- For any new data/job format, demonstrate old-reader compatibility or drain old consumers before enabling production writes. The SQL packet does not establish dual-write, job versioning or idempotency support.

**Gate:** migration coverage is complete, mismatch count is zero, every repair is accounted for, and reconciliation finds no continuing drift.

### Phase 3 — Verify and canary

Exercise both application versions and applicable worker versions against dedicated tenant fixtures. Check effective access, pipeline results and integrity during concurrent traffic.

**Gate:** all applicable existing test contracts pass through the real supported access surface; unauthorized visibility is zero; no integrity drift or rollout-induced error increase.

### Phase 4 — Contract

Only after old processes, pooled sessions and queued work are retired:

- validate added constraints;
- enforce stronger nullability or accepted-value restrictions;
- retire compatibility representations;
- complete intended access revocations.

If `M15` is already deployed, preserve its effective access boundary during rollback. If staging equivalent hardening elsewhere, apply it only after clients have proved compatibility with the five public views and their actual permissions (`M15:15–22`).

## 4. Explicit rollback boundaries

| Boundary | Safe rollback |
|---|---|
| Before migration commit or data writes | Abort the active transaction. For already-committed additive objects, retain them while reverting application deployment unless removal is independently safe. |
| After compatible new writes | Application rollback is safe only if old binaries can read, update and process all resulting rows/jobs. Prefer leaving additive schema in place. |
| After backfill or tenant repair | Use the repair ledger/before-images and reconcile subsequent writes. DDL reversal does not restore original values or ownership. |
| After new-only values or job formats | Drain, translate or otherwise make them old-compatible before restoring old consumers. Binary rollback alone is unsafe. |
| After privilege/policy changes | Restore only an audited compatible grant/policy set. Do not disable RLS or broadly regrant `ALL` as an availability fix. Exact prior privileges cannot be reconstructed from `M15` alone. |
| After dropping old representations | Old-version rollback requires reconstruction or restore plus reconciliation. This is a deliberate compatibility boundary. |
| After cascading deletion | Recover deleted data from retained evidence/backup and reconcile intervening writes. Recreating constraints or tables cannot undo deletion. |

A whole-database restore can discard unrelated tenant writes after the restore point. It is a recovery operation, not a transparent tenant-local rollback.

## 5. Measurable deployment checks

Run these before and after, with fixture-specific attribution and the same execution-role matrix:

- **Integrity:** zero survey/asset tenant mismatches and zero observation/survey tenant mismatches; zero orphaned parent references; count stale membership user IDs against `auth.users` for investigation. These checks derive from `M02:24–29` and `M03:27–30,44–47`.
- **Membership/isolation:** A has exactly one pilot membership, B has none; A sees its fixture, B sees zero pilot rows; repeat in the other direction with B’s tenant (`IT:40–52`; `RT:188–231`). Exercise unfiltered queries too, not only caller-supplied tenant filters.
- **Write isolation:** unauthorized insert, tenant reassignment and cross-tenant parent references fail under every relevant writer role. Include the multi-tenant-member case. Keep expected SQL privilege denial distinct from RLS or FK rejection.
- **Security catalog:** all intended tenant tables have RLS; policy expressions match intent; Directus has `rolsuper=false`, `rolbypassrls=false`, `rolcanlogin=true` (`RT:116–131`; `IT:349–357`). Also check ownership and helper EXECUTE privileges.
- **Read surface:** member fixture data is visible and outsider data exposure is zero for each of the five public API views (`M15:16–21`). Preserve applicable internal-view checks from `IT:315–337`.
- **Controlled ingestion fixture:** at least 3 assets, 2 manifests, 2 parse jobs, 6 surveys spanning 3 assets, 15 observations, 3 deltas, 1 deteriorating and 1 severe result (`IT:75–150`). Verify repeated processing does not introduce unintended duplicates.
- **Directus fixture:** unit-cost update reads back `70.00`; two LOS targets; four AMP sections and at least one version; one resolved unmatched fixture; uploaded test file at the specified tenant path (`IT:160–302`). Core-table access remains blocked under the intended access contract.
- **Operational:** record lock wait duration, deadlocks, permission/FK failures, batch duration, replication lag where applicable, and job backlog age. Set explicit stop thresholds before deployment; the packet supplies no production performance budgets.

## Alternatives, uncertainty and next action

- Blanket grants are not a safe compatibility solution; disabling RLS is not a safe rollback.
- A `viewer` write vulnerability is **conditional on effective grants**, not proven solely by its permissive policy.
- Public-view leakage, Directus correctness and worker incompatibility are unresolved—not demonstrated failures—because their implementations and runtime privileges are outside the packet.
- The next useful action is a **deployed catalog/role inventory plus a corrected, two-tenant compatibility test matrix**, before changing either data or permissions.

MATERIAL_EVIDENCE_CONFLICT: `M15:7–22` revokes authenticated access to `app` tables and grants five public API views, while `RT:276–283` expects authenticated users to query `app.asset` successfully; additionally, the “own events only” statement at `M08:68` conflicts with the tenant-member read allowance at `M08:71–73`.

Primary judge's stated reason

Slight forced preference for B because its explicit watermark warning helps prevent an unsupported catch-up or recovery assumption on a populated database. This is not an established material quality difference: A's proposed journaling and reconciliation are compatible with the same safeguard, and A retains a more explicit upload check. An independent review could reasonably prefer A.

This reason is the judge's assessment. No independent factual-defect finding is asserted by this record.

Battle wave: e1d38d25-feb4-4436-82c7-b4ad3c059a64. Pair: brp1_34f92d028e34f032458cf60b6b9f416a90b91c0e258af5ed118ec92fa76d78cf. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.