openai / gpt-6.1-sol / low / low effort preferred over deepseek / deepseek-flash / none / unknown effort · clear 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 / low / low effort answer
## Assessment
**Do not replay these migrations or apply the hardening change ahead of mixed-version compatibility checks.** The safe approach is additive expansion, verified tenant-consistent migration, then delayed privilege/schema contraction. The supplied tests are useful acceptance contracts, but they do **not** establish that the deployed schema currently satisfies them.
This was an independent, read-only analysis of the supplied snapshot; no tests were run.
Citation shorthand below: `00002`, `00003`, `00008`, and `00015` refer to the corresponding files under `supabase/migrations/`; `integration` and `rls` refer to `supabase/test-integration.sql` and `supabase/test-rls.sql`.
## Findings and risks
### 1. Ordering and mixed-version compatibility — high confidence
- Foundation precedes core tables: assets reference tenants; surveys reference assets; observations reference surveys (`00002:12–30`; `00003:6–55`).
- Policy installation requires more than the foundation/core migrations: `00008:52–66` names additional tables, and `00008:69–77` requires `audit_event`. Their definitions are outside this packet. Historical numbering is not proof that those dependencies exist in the deployed database.
- These scripts are not safe general-purpose reconciliation scripts. `CREATE TABLE IF NOT EXISTS` does not upgrade an existing table definition; indexes in `00002:52–53` and named policies in `00008:71–91` are not guarded against existing objects.
- **Hardening is a compatibility-breaking permission contraction.** It revokes authenticated access to all existing app tables, sequences, and functions, while granting SELECT on only five public views (`00015:4–22`). Old clients using direct app-table access or app-function calls may fail after commit. Whether any actual API or worker does so is unknown.
- `00015` requires all five public views to exist. Their definitions, ownership, security mode, grants, and tenant filtering are not supplied; a SELECT grant alone does not prove safe or functional access (`00015:16–22`).
- The database search-path change is not an application compatibility guarantee. Long-lived connections and application-specific search paths must be checked rather than assumed uniform (`00002:8–9`).
**Implication:** keep old object names, column meanings, and required access working until every active service, worker, scheduled task, and pooled connection has been shown compatible with the replacement access path.
### 2. Tenant integrity is weaker than row-level membership — high confidence
Each child has its own tenant FK, but parent links reference only the parent UUID:
- `survey.tenant_id → tenant.id`, independently of `survey.asset_id → asset.id` (`00003:29–30`).
- `observation.tenant_id → tenant.id`, independently of `observation.survey_id → survey.id` (`00003:46–47`).
Consequently, the supplied constraints do **not** enforce matching tenants across either relationship. A survey labeled tenant A can reference an asset belonging to tenant B if the referenced UUID exists; the same issue applies to observations.
Standard policies check membership only against the row’s `tenant_id`, not its parent’s tenant (`00008:36–45`). This does not repair the relational gap. Whether application validation prevents such writes is unproven.
**Implications:**
- Existing mismatches can distort tenant joins and derived results; exact exposure depends on unavailable view/function definitions.
- Cascading parent deletion can delete differently labeled child rows because the cascade follows the UUID FK, not tenant equality (`00003:30,47`).
- Before adding composite tenant-parent constraints, measure and resolve every mismatch. Do not automatically relabel rows without an authoritative ownership decision.
### 3. Authorization and isolation caveats — high confidence for definitions; deployment behavior unverified
- Membership ignores membership role (`00002:36–47`). Standard modification policies authorize **any member**, including viewers (`00008:42–45`), despite the viewer “read-only” comment (`00002:33`). Effective writes still require SQL privileges; hardening removes direct authenticated privileges, but restoring broad old grants could reactivate this policy behavior.
- The “mod” policy uses `FOR ALL`, so it also applies to SELECT; the separate SELECT policy does not narrow it (`00008:36–45`).
- The RLS sweep covers app base tables existing at that moment. It does not automatically enable RLS or install policies on future tables (`00008:6–18`).
- RLS is enabled, not forced. Table owners and bypass-capable roles require separate scrutiny; policy existence is not proof that a production connection is subject to it (`00008:16`; `integration:349–359`).
- `app.is_member` and `app.apply_member_policies` are security-definer functions without a declared fixed search path (`00002:36–47`; `00008:21–47`). The latter also interpolates table input into privileged dynamic SQL. Its executable audience, owner, and exposure must be audited; exploitability is not established by the packet.
- Revocation from `authenticated` does not itself remove privileges inherited through other roles or PUBLIC. Likewise, default-privilege alterations need to be verified for every actual object-creating role (`00015:7–13`).
- Audit behavior is broader than its comment: tenant members can read other users’ tenant events; insertion checks the user identity but shows no tenant-membership check (`00008:68–77`).
- `tenant_member.user_id` has an auth-user reference comment, not an actual FK (`00002:24–29`). Orphan membership UUIDs therefore need an explicit check.
**Implication:** do not treat hardening as proof of complete isolation, and do not roll it back by indiscriminately restoring all authenticated privileges.
### 4. Test limitations and conflicts — high confidence
- Integration outsider and view tests use `SET ROLE postgres` (`integration:54–60,312–337`). Setting a JWT subject does not make a superuser, table owner, or bypass role obey RLS. Inspect role attributes; run acceptance queries through genuinely non-bypassing production-equivalent roles.
- The RLS script explicitly acknowledges that service-role SQL cannot prove outsider isolation (`rls:170–185`) and asks for real authenticated testing (`rls:276–285`).
- Tests mostly contain comments describing expected results, not executable assertions that fail deployment automatically.
- Tests query app tables/views, while hardening explicitly directs authenticated REST access to public views (`integration:315–336`; `rls:279–283`; `00015:15–22`). After hardening, direct authenticated app queries may correctly return permission errors rather than zero rows.
- Integration expects `app.is_directus()` policies, but the supplied standard policies contain only `app.is_member()` (`integration:377–390`; `00008:36–65`). Other policy migrations could explain this; their behavior is not evidenced here.
- Survey and observation fixtures are not retry-idempotent: random UUID defaults and no shown business-key uniqueness mean `ON CONFLICT DO NOTHING` does not prevent repeated logical inserts (`00003:27–55`; `rls:82–102`).
- Integration cleanup includes tenant-wide section and LOS-target deletion. It is unsafe on existing production tenant data (`integration:426–432`).
## Phased rollout
### Phase 0 — Baseline and admission gates
1. Capture deployed definitions, policy expressions, effective grants, owners, default ACLs, RLS flags, and role attributes. Compare actual state to the supplied definitions rather than replaying history.
2. Establish a restorable backup/PITR position and test restoration separately.
3. Record per-tenant counts and invariant violations:
- survey/asset tenant mismatches: **0 required**;
- observation/survey tenant mismatches: **0 required**;
- orphan memberships relative to auth users: investigate every result;
- duplicate proposed business keys: **0 before introducing uniqueness**.
4. Inventory connection identities and old/new version database access. No application routes or worker implementations are supplied, so compatibility must be demonstrated operationally.
5. Establish lock-wait, deployment-duration, error-rate, and queue-age abort thresholds before rollout.
### Phase 1 — Expand
- Add replacement columns, tables, or views without dropping or renaming existing contracts.
- Configure least-privilege grants and tenant policies before exposing new objects; the historical RLS sweep will not cover them automatically.
- Preserve old writes unless they would violate a necessary safety invariant. If a stricter tenant constraint rejects existing writers, stop and correct those writers before enforcement.
- For tenant-consistent parent links, prepare parent uniqueness on `(tenant_id, id)` and composite child FKs as a proposed corrective migration—not as existing behavior.
**Lock controls:** use bounded lock/statement timeouts and avoid long DDL transactions. For large tables, assess concurrent index construction and staged constraint validation. Adding a `NOT VALID` FK still enforces new writes; it is not a compatibility bypass. These are PostgreSQL deployment recommendations, not operations present in the supplied migrations.
### Phase 2 — Migrate
- Backfill only when a concrete replacement representation is defined. None is specified in the packet.
- Use bounded, resumable batches and stable identifiers; monitor lock waits, WAL growth, replica lag, and foreground latency.
- Account for concurrent old/new writes through a documented consistency mechanism. Dual-writing, triggers, or change capture are alternatives—not observed application behavior.
- Quarantine tenant mismatches for ownership resolution. Retain an audit trail of repairs and before-values.
- Keep incompatible new-format writes disabled until their rollback representation is defined.
### Phase 3 — Verify and canary
Use isolated fixtures, then production read-only checks:
| Contract | Measurable gate |
|---|---|
| RLS enabled and named policies | Required core tables show RLS enabled; inspect actual policy expressions, not just names (`rls:116–131`). |
| Membership and cross-tenant access | Member sees own fixture; outsider sees **0** pilot rows; second-tenant member sees only its tenant (`rls:162–231`). |
| Public access surface | Exercise all five granted public views as member and outsider; outsider exposure **0**, with positive authorized fixtures (`00015:16–22`). |
| Ingestion | Isolated golden fixtures meet **3+ assets, 2+ manifests, 2+ parse jobs, 6+ surveys, 15+ observations, 3+ deltas, 1+ deteriorating, 1+ severe** (`integration:75–150`). |
| Directus functionality | Unit costs editable to **70.00**; LOS, AMP, unmatched-resolution, and S3-path contracts pass (`integration:160–302`). |
| Directus security | `rolsuper=false`, `rolbypassrls=false`; core data inaccessible; required back-office policy behavior verified (`integration:347–390`). |
| Integrity and migration | Tenant mismatches **0**; backfill backlog **0**; reconciliation differences **0**, except explicitly approved changes. |
Distinguish “query denied” from “query succeeded with zero rows.” Both can prevent exposure, but they are different compatibility outcomes.
Canary old/new service and worker combinations against these gates. The golden counts are fixture-specific minimums, not production-wide correctness proofs.
### Phase 4 — Contract
Only after old versions and outstanding old-version jobs are drained:
- Apply justified privilege contraction, including `00015`-style restrictions.
- Validate strengthened constraints and retire obsolete representations.
- Keep compatibility objects for a declared observation window.
- Do not drop old fields or access paths merely because new-version smoke tests pass.
## Rollback boundaries after writes
- **Before transaction commit:** `00015` is explicitly transactional (`00015:1–24`); failure can roll back its own privilege changes. Do not infer equivalent wrapping for the other supplied files.
- **After privilege-only commit:** restore the captured, approved ACL state with a new migration if necessary. There is no data transformation in `00015`, but restoring broad grants may reopen viewer writes or unsafe helper access.
- **After backward-compatible writes:** roll application versions back only if old readers and writers can handle every committed value. Retain additive schema and valid constraints where possible.
- **After tenant repairs/backfills:** do not reverse repairs blindly. Concurrent writes can make saved before-values stale; rollback requires write coordination and reconciliation.
- **After incompatible new writes:** application rollback alone is unsafe. Fence affected writes, drain workers, and either use a verified reverse transformation or forward-fix. No such transformation is supplied.
- **After dropped data or cascaded deletion:** re-creating schema does not recover data. Use scoped recovery or coordinated restore; whole-database restoration risks losing unrelated post-backup tenant writes (`00002:25`; `00003:8,29–30,46–47`).
- External ingestion and file uploads are not undone by database rollback (`integration:80–93,291–302`).
## Next useful action
Produce a deployment-state comparison and compatibility matrix first, then execute the existing contracts with isolated fixtures and real non-bypassing identities. Gate contraction on tenant-invariant checks and explicit proof that no active old-version component requires revoked access.
MATERIAL_EVIDENCE_CONFLICT: The membership-role comment promises viewer read-only access (`00002:33`), while standard modification policies authorize any member (`00008:42–45`); the tests expect direct app-table access and Directus-specific policies (`rls:279–283`; `integration:377–390`), while hardening revokes authenticated app-table privileges and the supplied policies contain only membership checks (`00015:7–22`; `00008:36–65`).
deepseek / deepseek-flash / none / unknown effort answer
## Evidence packet
### 1. Conclusion and recommendation
The snapshot is a **tenant-isolation-first schema with a working expand-friendly core**, but it is **not safe to roll out as a single idempotent migration set during mixed-version operation without staging**. The strongest, provable risks are: (a) `00002` mutates a **database-wide GUC** (`search_path`) the moment it runs; (b) `00008` enables RLS and installs policies via a `do $$` loop over **all** `app` base tables, then immediately references tables (`app.asset_delta`, `app.manifest`, `app.job`, `app.unmatched`, `app.unit_cost`, `app.los_target`, `app.amp_sections`, `app.amp_versions`, `app.kpi_card_defs`, `app.saved_views_meta`, `app.semantic_registry`, `app.doc_index`) and views (`public.api_*`) and roles (`directus`, `app.is_directus()`) that are **not defined anywhere in this packet**; (c) `00015` revokes broad privileges on **all** tables/sequences/functions in `app` from `authenticated` and grants only five `public.api_*` views. Any of these can break old service code during mixed-version rollout. The recommended shape is a **staged expand → migrate/ship-compatible → verify → contract**, with the migration files treated as already-applied baseline and new work delivered as *additive* migrations only.
### 2. Proven behavior (grounded in the supplied files)
- **Tenant model**: `app.tenant` has `id` UUID PK default `gen_random_uuid()`, `slug` unique not null (`00002:12–18`); `app.tenant_member` PK `(tenant_id, user_id)`, cascades on tenant delete, role constrained to `('admin','manager','viewer')` (`00002:24–30`).
- **Membership helper**: `app.is_member(_tenant uuid)` returns boolean, `stable security definer`, checks `tenant_member` for `auth.uid()` (`00002:36–47`). Security-definer nature is important: it can read `tenant_member` regardless of caller RLS, so it is the linchpin of every policy.
- **RLS enablement is dynamic**: `00008:6–18` loops `information_schema.tables` where `table_schema='app' and table_type='BASE TABLE'` and runs `alter table … enable row level security`. This means **any table added later in `app` is NOT automatically RLS-enabled** unless it could be seen at the time `00008` ran or a similar loop reruns. That is a real backward-compat hazard when old code and new code coexist.
- **Policy generation is helper-based and explicit-list**: `app.apply_member_policies(tbl_name)` drops/creates `r_<t>_select` (SELECT, `using app.is_member(tenant_id)`) and `r_<t>_mod` (ALL, `using`+`with check app.is_member(tenant_id)`) (`00008:21–47`). It is called for a fixed list of 15 tables (`00008:52–66`). Tables **not** in the list have RLS enabled by the loop but **no policy**, i.e. default-deny for non-superusers. That is a silent functional break for any table existing at `00008` time but omitted from lines 52–66.
- **Audit path is special-cased**: `audit_event` gets SELECT (`user_id = auth.uid() or app.is_member(tenant_id)`) and INSERT (`with check user_id = auth.uid()`) (`00008:69–77`). **No UPDATE/DELETE policy** exists for `audit_event` → once RLS is on, updates/deletes from `authenticated` are denied (default-deny). Correct for audit immutability, but old code that “fixes” an audit row will fail.
- **`tenant` and `tenant_member` are read-limited**: only SELECT policies (`tenant_select` `app.is_member(id)`, `tenant_member_select` `user_id = auth.uid()`) (`00008:80–91`). No INSERT/UPDATE/DELETE policy on either → tenant onboarding/membership edits via `authenticated` will be **denied** post-RLS. This is a likely real regression for admin flows.
- **Privilege hardening is global and one-shot**: `00015` is wrapped in `begin; … commit;` (`00015:1,24`), revokes `all` on `schema app` from `authenticated` then `grant usage` (`00015:4–5`), revokes all on **all tables, sequences, functions** in `app` (`00015:7–9`), sets default privileges to revoke (`00015:11–13`), and grants SELECT only on five `public.api_*` views (`00015:16–22`).
- **Test contract exists and is explicit**: `test-rls.sql` defines the operational PASS checks — RLS enabled on `asset/survey/observation` (`test-rls.sql:117–122`), policies `r_<table>_select`/`r_<table>_mod` exist (`test-rls.sql:125–131`), non-member sees 0 (`test-rls.sql:163–168`), cross-tenant isolation with two tenants (`test-rls.sql:188–231`), views respect RLS (`test-rls.sql:238–239`). `test-integration.sql` defines role checks (`directus` must be `rolsuper=false, rolbypassrls=false`, B5.1 lines 349–359), core-table denial (B5.2 lines 361–375), and a **literal expectation that policies include `app.is_directus()`** (B5.3 lines 379–390).
### 3. Concrete risks
**Ordering / dependency risks**
- `00008` depends on the `app` schema and on tables beyond `00002`/`00003` (it references `audit_event`, `asset_delta`, `manifest`, `job`, `unmatched`, `unit_cost`, `los_target`, `amp_sections`, `amp_versions`, `kpi_card_defs`, `saved_views_meta`, `semantic_registry`, `doc_index` at lines 55–66, 69). Those are **not in the packet**. If any listed table is absent when `00008` runs, `app.apply_member_policies('<missing>')` raises `relation does not exist` and, because the calls are plain `select` statements outside an explicit transaction in the file text shown, earlier statements may already have committed. **Consequence**: partial RLS state — some tables RLS-on with policies, later ones not yet enabled. Confidence: high (logic) / medium (actual ordering, since intermediate migrations 00004–00014 are not supplied).
- `00015` grants SELECT on `public.api_asset_geojson`, `api_top_deteriorating`, `api_new_severe`, `api_repeat_om`, `api_coverage_health` (`00015:16–22`). Those views are **not defined in the packet**. If they do not exist at `00015` time, the whole `begin;…commit;` rolls back → the hardening does **not** apply, and `authenticated` retains broad grants. Confidence: high that this is a hard-fail-or-noop branch; medium on which branch actually occurs (views presumably created in an earlier not-supplied migration; the API view names in the integration checks (`public.api_*`) suggest they exist).
- `00002:9` `alter database postgres set search_path = app, public, extensions;` is a **cluster-adjacent, database-scoped** change that affects new sessions. During mixed-version rollout, any code relying on `public`-only resolution or on unqualified names now resolves `app` first. This is a prime candidate for “worked in dev, broke in prod.” Confidence: high that the setting is applied; not proven here whether app code depends on it.
**Mixed-version compatibility risks**
- Old API nodes expecting to read/write `app.*` directly as `authenticated` will be **revoked** by `00015:7–9`. Only `public.api_*` SELECTs remain (`00015:16–22`). No INSERT/UPDATE/DELETE grant to `authenticated` exists after `00015`. So if any live code path writes via the `authenticated` role to `app` tables, it breaks at hardening time. Confidence: high from the grants; impact depends on app code not in packet.
- RLS is enabled per-table by a loop snapshot at `00008` time. Tables created *after* that migration (plausibly anything in 00004–00014 or newer) rely on their own migration enabling RLS. If a recent table exists without RLS, mixing new code with old DB or vice-versa can **expose rows across tenants**. This is the single highest-severity hypothesis; it is **not provable** because the intermediate migrations aren’t in the packet. Flag as dependency.
- `is_member` is `security definer` but has **no explicit `set search_path`** in its definition (`00002:36–47`). Under a changed DB `search_path` (`00002:9`) a security-definer function without a pinned `search_path` is a classic privilege-escalation/instability surface. Confidence: medium-high as a hardening gap; actual exploitability requires objects in `app` (or `extensions`/`public`) that a low-privilege role can manipulate — not established here.
- Role-specific denial: `directus` role is assumed by tests (`test-integration.sql:163,203,223,264`) and expected to see `is_directus()` policies (line 388), but **no `is_directus()` function and no directus-specific policies appear in `00008`**. `00008` only creates member policies. So either (a) directus policies live in a not-supplied migration, or (b) the integration test’s B5.3 expectation cannot currently be met. Either way this is a **compatibility gap to verify before relying on Directus during rollout**. Confidence: high that the packet lacks them; the tests explicitly expect them.
**Lock / backfill risks**
- No DDL here rewrites large tables (`00002`/`00003` are creates; `00008` enables RLS; `00015` changes grants). `enable row level security` takes a brief `ACCESS EXCLUSIVE` lock but is metadata-only and fast; `revoke/grant` is also fast metadata. So lock risk is **low** for these exact statements. Confidence: high.
- Backfill risk is **unspecified**: nothing in the packet computes `asset_delta`, `coverage`, etc. `app.compute_deltas()` is invoked as a bare `select` in the test plan (`test-integration.sql:140`), implying a function exists outside the packet. During rollout, concurrent `compute_deltas()` runs across mixed workers could race on `asset_delta`. This is plausible but **unproven** here.
- `test-integration.sql:169` uses `on conflict (tenant_id, method, diameter_in)` for `app.unit_cost`; this asserts a unique constraint exists on those columns. Not shown in `00002`/`00003`, so the constraint is defined elsewhere. Same for `los_target(tenant_id, metric)` (`:209`) and `amp_sections(tenant_id, section_key)` (`:232`). Fold into dependency list.
**Integrity / tenant-isolation risks**
- `app.tenant_member.user_id` has **no FK to `auth.users`** (`00002:26`, comment says “references auth.users(id)” but no constraint). This is intentional (referencing an external schema) but means orphan memberships are possible; `is_member` would then authorize a user ID that no longer exists. Low direct isolation risk (UUID collision effectively impossible) but data-integrity gap. Confidence: high, from the absence of constraint.
- `asset_delta`, `manifest`, `job`, `unmatched`, `unit_cost`, `los_target`, `amp_*`, `kpi_card_defs`, `saved_views_meta`, `semantic_registry`, `doc_index` are all assumed to have a `tenant_id` because `apply_member_policies` builds `using (app.is_member(tenant_id))` (`00008:38,44`). If any of those tables lacks a `tenant_id` column, the policy creation **fails at DDL time** → cascade of the ordering risk above. Confidence: high as a fail mode; the column’s presence is not proven in the packet.
- Cross-tenant leak via `public.api_*` views: `00015` grants **SELECT on the views** to `authenticated` (`00015:16–22`). If those views are `security definer` or owned by a role that bypasses RLS, they could leak across tenants regardless of base-table RLS. The test plan asserts views inherit RLS (`test-integration.sql:305–341`, `test-rls.sql:233–241`), but the view definitions are not in the packet, so **view security mode is unverified**. This is the most material isolation uncertainty. Confidence: high that it is unverified; consequence potentially severe.
- `audit_event` has no UPDATE/DELETE policy, consistent with tamper resistance, but any old code that “closes out” audit records will now silently affect 0 rows or error. Confidence: medium (behavioral).
**Rollback risks**
- `00015` is transactional (`begin;…commit;`), so that file alone is atomically reversible **if** a matching inverse migration is written. However, `00008` is **not** written as an explicit transaction and uses dynamic DDL in a loop; a partial failure leaves partial RLS. Rolling back RLS requires `alter table … disable row level security` plus `drop policy` for each — but disabling RLS on a table that is now the *only* isolation mechanism re-exposes tenant data instantly to any authenticated caller still holding SELECT (see `00015` grant asymmetry: after `00015`, `authenticated` has no direct `app` table grants, so disabling RLS without restoring grants doesn’t leak mid-flight — but if you roll back `00015` first, you restore nothing either, since `00015` only *revoked*; the pre-`00015` grants came from earlier defaults/YAML not in packet). **Key rollback boundary**: once `00015` commits, rolling back the schema without a written inverse leaves `authenticated` under-revoked or over-privileged unpredictably because the original grant baseline is not captured. Confidence: high.
- `00002:9` database-level `search_path` alteration is easy to revert (`alter database postgres reset search_path`) but affects all sessions immediately; a mid-flight revert changes name resolution for running app versions.
- Data writes during rollout: any writes to `app.*` by new code between `00008` and a rollback must be preserved. Because `00008` adds no columns, no data migration is needed for these three files — that is favorable. But writes to any table whose RLS was enabled without a policy would be *rejected*, not lost, so a rollback must also account for failed-write retries. Confidence: medium.
### 4. Measurable pre/post-deployment checks (using the existing test contracts)
Pre-deploy (baseline snapshot, read-only):
- Record `select tablename, rowsecurity from pg_tables where schemaname='app'` — expect `true` for `asset/survey/observation` per `test-rls.sql:117–122`; enumerate **all** `app` tables and flag any with `rowsecurity=false` (fills the `00008` loop gap concern).
- Record `select tablename, policyname, cmd from pg_policies where schemaname='app'` — expect `r_<t>_select` + `r_<t>_mod` for the 15 listed tables (`test-rls.sql:125–131`, `00008:52–66`); flag listed tables with no policy and unlisted tables with RLS but no policy.
- Confirm existence of the tables/policies the tests assume but the packet omits: `app.asset_delta`, `manifest`, `job`, `unmatched`, `unit_cost`, `los_target`, `amp_sections`, `amp_versions`, `audit_event`, `app.is_directus()`, `app.compute_deltas()`, the unique constraints at `test-integration.sql:169,209,232`, and the six `public.api_*` views in `00015:16–22`. Any absence invalidates parts of the test contract.
- Record `select rolname, rolsuper, rolbypassrls, rolcanlogin from pg_roles where rolname='directus'` expecting `false/false/true` (`test-integration.sql:349–359`).
- Capture `select current_setting('search_path')` and the DB-level setting for `postgres` to detect pre-existing drift from `00002:9`.
Post-deploy (must-pass gates):
- Outsider/non-member sees 0: replicate `test-integration.sql:54–64` (set jwt sub for outsider, count `app.asset` = 0) and `test-rls.sql:163–166` membership_count = 0.
- Cross-tenant: create second tenant, add non-member there, assert each user sees only their tenant’s assets (`test-rls.sql:188–231`).
- Views inherit RLS: member sees >0, outsider sees 0 across the eight views in `test-integration.sql:316–323` and `test-rls.sql:238–239`.
- Back-office RLS includes `is_directus()`: run the query at `test-integration.sql:379–386` and require the qual to contain `app.is_directus()`. If it does not, B5.3 is red — this is a likely failure given the function is absent from `00008`.
- Directus cannot touch core data: `test-integration.sql:361–375` expects 0 rows from `asset/survey/observation/asset_delta` under `set role directus`.
- Privilege gate after `00015`: assert `authenticated` has no direct `app` table privileges except via view ownership, and SELECT on exactly the five `public.api_*` views (`00015:16–22`); assert `has_table_privilege('authenticated','app.asset','SELECT') = false`.
- Negative/grant test for the write paths used by old workers: identify every role the app uses (only `authenticated`, `directus`, and `service_role` are named/implied by the packet) and confirm the privilege needed. **Unknown roles → cannot gate; flag.**
- Audit immutability: confirm `authenticated` cannot UPDATE/DELETE `audit_event` (no matching policy, `00008:69–77`) and the insert path enforces `user_id = auth.uid()`.
Metric thresholds (derived, not invented APIs): all RLS coverage = 100% of `app` base tables (`rowsecurity=true`), 0 tables with RLS and no policy, cross-tenant probe returns 0 rows for non-member on every generated test view and each core table listed in `00008:52–66`.
### 5. Phased expand / migrate / verify / contract plan
- **Phase 0 — Inventory (read-only).** Resolve the dependency list from §4 pre-deploy. Output: a matrix of tables, RLS flag, policy set, tenant_id presence, unique constraints, and grants. Gate: no listed table missing `tenant_id`; every table in the `00008:52–66` list exists.
- **Phase 1 — Expand (additive only).** Do **not** re-run `00002`/`00008`/`00015` as-is. Instead:
- Additive migration to freeze `search_path` on `app.is_member` and any other security-definer helper (`set search_path = app, pg_temp` form; not present in `00002:36–47`, so this is a gap-closure, not a change to shown behavior).
- Additive migration to **coverage-complete** RLS: a loop that enables RLS on every `app` base table **and** generates a policy for private tables not in the current list, plus explicit `is_directus()` policies if Directus is in scope (`test-integration.sql:388`). This replaces the fragile snapshot behavior of `00008:6–18` with a repeatable invariant, so old/new versions converge.
- No columns added in these three files → no data backfill strictly needed for the shown schema. Any backfill belongs to the not-supplied delta/compute path.
- **Phase 2 — Migrate (compatible writes).** Keep base-table access **unchanged** during the transition: do not apply `00015`’s global revoke until read paths are cut over to `public.api_*`. If `00015` must run early, expand first by granting the minimum needed so old writers keep working, then contract later.
- **Phase 3 — Verify.** Run the §4 post-deploy gates in a transaction-scoped impersonation harness matching the tests (`set role postgres; set request.jwt.claim.sub = …`, `test-integration.sql:55–56,312–313`). All gates must be green; specifically the `is_directus()` qual check and the view-RLS counts.
- **Phase 4 — Contract.** Only after all readers/writers use `public.api_*` (or another granted path): apply `00015` (`00015:7–9` revoke + `00015:16–22` grant). Assert the privilege gate. This is the **first irreversible-after-writes boundary** — capture the exact pre-state grants first, because `00015` only revokes and the baseline grant set is not recorded in the packet.
### 6. Explicit rollback boundaries after writes
- **Boundary A (before `00015` commits):** reversible by dropping the new RLS/policies added in Phase 1. Data unaffected (no schema columns). Safe.
- **Boundary B (after `00015` commits, before app cutover):** rollback requires a written inverse that **re-grants** the exact pre-`00015` privileges. Those are not derivable from the packet — without a captured baseline, rollback is unspecified. **Do not cross this boundary without a captured grant inventory.**
- **Boundary C (after new-version writes via views):** rollback must preserve inserts made through `public.api_*` and/or `authenticated`-gated paths. Because `00015` leaves no direct DML grant, confirm which role actually writes before planning; this is an open dependency.
- **Boundary D (`00002:9` search_path):** independently revertible (`reset search_path`) but affects all live sessions; treat as a separate, explicitly-announced step, not part of a bulk migration rollback.
### 7. Alternatives, discarded hypotheses, likely false positives
- *Discarded:* “These migrations rewrite big tables and will lock `app.asset`.” No `alter table … add column`/`type change`/`set not null` appears; the only table DDL is `enable row level security` (`00008:16`). Low lock risk.
- *Alternative reading of `00008` loop:* it may intentionally capture only the tables that exist at that point, with later tables handled by their own migrations. If so, the coverage gap is not a bug but a convention. This can only be decided from the missing 00004–00014 files — treated as a hypothesis, not a proven defect.
- *Likely false positive:* “`is_member` is exploitable via search_path.” `security definer` is declared (`00002:40`), but without a pinned `search_path` (`00002:36–47`) the risk is real in principle and unproven in practice; do not claim an exploit.
- *Not a conflict:* the tests assume `is_directus()` and directus policies; their absence from `00008` is most likely “defined in a file outside this packet,” not “the schema contradicts its tests.”
### 8. Missing evidence / dependencies and consequences
- Migrations 00004–00014 (absent): determine real table set, `is_directus()`, `compute_deltas()`, the `public.api_*` view definitions, and unique constraints used at `test-integration.sql:169,209,232`. Without them, RLS coverage, view security mode, and privilege baseline cannot be confirmed.
- `public.api_*` view security mode (invoker vs definer/owner): decides whether the `00015` grants leak across tenants. Highest-consequence unknown.
- Actual role set used by live app/workers (only `authenticated`, `directus`, `service_role` appear/imply): determines which `00015` revokes break real traffic.
- Application code (explicitly not in scope): determines whether old versions depend on `search_path` ordering and direct `app` writes. All such claims here are marked as assumptions.
### 9. Next useful action
Produce the Phase-0 inventory query set from §4 against a **production-like read-only replica**, plus a `pg_dump --schema-only`-style extraction of `pg_policies` and `information_schema.role_table_grants` for `authenticated`/`directus`. That single snapshot resolves the top three uncertainties (RLS coverage gaps, view security mode, and the pre-`00015` grant baseline) and converts Boundaries B/C from “unspecified” to “reversible.”Primary judge's stated reason
A provides a materially safer assessment: its verification plan avoids treating privileged queries as proof of isolation, and its integrity and rollback analysis better addresses existing tenant data and mixed-version writes. This is a supported clear preference, not merely a forced slight choice. Actual deployed role attributes, application access patterns, and runtime outcomes remain unknown.
This reason is the judge's assessment. No independent factual-defect finding is asserted by this record.
Battle wave: d1711a3f-9f3b-4640-a160-e32f42e27c5f. Pair: brp1_4a522b9f1fe2bcffd76de6110d669c9ffe9e1fbaad4ee09c4c770b99b783e3fe. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.