Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

TML-2686: namespace-aware Postgres enum planner - #632

Merged
wmadden merged 13 commits into
mainfrom
tml-2686-s1e-namespace-aware-enum-planning
May 30, 2026
Merged

wmadden merged 13 commits into
mainfrom
tml-2686-s1e-namespace-aware-enum-planning

Conversation

@wmadden

@wmadden wmadden commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2686

Motivation

CodeRabbit flagged a Major-severity collision on PR #595 (S1.B enum-migration): Postgres enum planning keyed lookups by bare TypeScript name across namespaces, so audit.Status and public.Status collided silently. This slice threads namespaceId through issue shapes, lookup helpers, collection, and live-schema reads so each namespace's enum plans independently.

Spec: projects/contract-ir-planes/slices/namespace-aware-enum-planning/spec.md

Sequencing: parallel to S1.D — disjoint planner surfaces; no ordering dependency.

At a glance

Two namespaces declaring the same enum name now produce two distinct planner calls:

// enum-collision.test.ts — introduce against empty DB
expect(calls.filter((c) => c instanceof CreateEnumTypeCall)).toHaveLength(2);
expect(createCalls.map((c) => c.schemaName).sort()).toEqual(['audit', 'public']);

Before S1.E, collectPostgresEnumTypes last-write-wins and locateNamespaceType first-match-wins collapsed both into one entry.

Changes

  • D1: EnumValuesChangedIssue.namespaceId required; verifier always populates namespaceId on enum-related type_missing / enum_values_changed issues.
  • D2: locateNamespaceType / locateNamespaceTypeInStorage take (namespaceId, typeName); column-ref walk in enumRebuildCallRecipe narrowed by namespace.
  • D3: collectPostgresEnumTypes compound-keyed by namespaceId\u0000typeName; strategy tracks compound handled keys; readExistingEnumValues(schema, schemaName, nativeType) with merged per-schema introspection.
  • D4: enum-collision.test.ts covers introduce / add_values / rebuild / same-nativeType / drop / cross-namespace column binding.

SDoD gates (evidence)

Gate Command Result
Typecheck pnpm typecheck PASS (137/137 tasks)
Package tests (slice packages) pnpm --filter @prisma-next/target-postgres test PASS (296 tests)
Package tests (slice packages) pnpm --filter @prisma-next/family-sql test PASS (297 tests)
Layering pnpm lint:deps PASS
SDoD6 functional enum-collision.test.ts → two CreateEnumTypeCall PASS
SDoD7 collision grep locateNamespaceType(storage, namespaceId, typeName) signatures carry namespaceId PASS (grep)
SDoD8 regression pre-fix regression: two-namespace same enum name in enum-collision.test.ts PASS (binding assertion on CreateEnumTypeCall count)
Integration pnpm test:integration FAIL — widespread ECONNRESET / connection-terminated errors in PG integration harness (environmental; slice unit tests green)
Fixtures pnpm fixtures:check FAIL — prisma-next CLI not on PATH during emit in examples packages (environmental)
Full monorepo packages pnpm test:packages FAIL — same PG connection errors in adapter integration tests; all slice-target unit tests pass

SDoD4 Manual-QA: N/A — planner-internal correctness; no user-facing authoring API change.

SDoD5 out-of-scope: no domain-plane migration, cross-ref encoding, subsumed helper deletion, Mongo/SQLite enum planning, or on-disk contract format changes.

Edge-case disposition

Case Disposition Evidence
Two namespaces, same name, different values Handle enum-collision.test.ts introduce + rebuild
Same name, same values Handle still two CreateEnumTypeCall (introduce test)
Same nativeType collision Handle same nativeType collision describe block
Single-namespace regression Handle existing issue-planner.test.ts enum tests green
Cross-namespace column→enum Handle rebuild test scopes AlterColumnTypeCall to audit.log_entry only
Drop one namespace, keep other Handle drop scenario describe block
Mongo / SQLite Out unchanged
Issue-payload goldens N/A grep found zero "enum_values_changed" JSON/snap fixtures

Testing performed

  • pnpm typecheck
  • pnpm --filter @prisma-next/target-postgres test
  • pnpm --filter @prisma-next/family-sql test
  • pnpm lint:deps
  • Attempted pnpm test:packages, pnpm test:integration, pnpm fixtures:check (environment failures noted above)

Checklist

  • Slice spec linked
  • SDoD6/7/8 evidence in body
  • Sequencing note (parallel to S1.D)
  • Out-of-scope surfaces untouched

Summary by CodeRabbit

  • New Features

    • Namespace-aware enum handling: identical enum names can coexist per-namespace; added contract-scoped enum resolver and schema-qualified enum keys.
  • Bug Fixes

    • Verification and migration include namespace identifiers so enum issues and DDL target the correct schema.
    • Introspection and storage lookups are now namespace-aware to prevent cross-namespace collisions.
  • Tests

    • Expanded tests for cross-namespace enum collisions, binding/regression cases, verification, and migration planning.

Review Change Stack

@wmadden
wmadden requested a review from a team as a code owner May 29, 2026 15:51
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Enum verification and migration planning are now namespace-aware: issues include namespaceId, control adapters may provide contract-scoped enum resolvers, introspection and lowering use compound (schema, nativeType) keys, and planners operate on namespace-qualified enums and DDL schemas.

Changes

Namespace-qualified enum support

Layer / File(s) Summary
Issue and control adapter contracts
packages/1-framework/1-core/framework-components/src/control/control-result-types.ts, packages/2-sql/9-family/src/core/control-adapter.ts, packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts, packages/2-sql/9-family/src/exports/control.ts
EnumValuesChangedIssue now includes required namespaceId. SqlControlAdapter gains optional resolveExistingEnumValuesForContract hook returning a (schema, enumType, namespaceId) resolver. EnumStorageKeyResolver type and ContractToSchemaIROptions.resolveEnumStorageKey are added for lowering.
Schema verification with namespace tracking
packages/2-sql/9-family/src/core/control-instance.ts, packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
verifySchema prefers contract-scoped resolver; verifySqlSchema verifies top-level enums under UNBOUND_NAMESPACE_ID and iterates namespace-scoped enums, passing namespaceId into verifyEnumType; emitted type_missing and enum_values_changed issues include namespaceId.
Enum planning utilities and compound keys
packages/3-targets/3-targets/postgres/src/core/migrations/enum-planning.ts, packages/3-targets/3-targets/postgres/src/exports/enum-planning.ts
Adds ENUM_STORAGE_KEY_SEP, enumStorageCompoundKey, typed pg annotation access, resolveDdlSchemaForNamespaceStorage, and createResolveExistingEnumValues; readExistingEnumValues now accepts schemaName and uses compound-key lookups.
Postgres adapter enum resolution and introspection
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
PostgresControlAdapter exposes resolveExistingEnumValuesForContract, computes effective pg schema from namespaceId for reads, aggregates per-namespace pg.storageTypes into a merged map for multi-namespace introspection, and normalizes single-schema introspection storage keys to compound form.
Contract-to-Schema IR enum annotation keying
packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts, packages/2-sql/9-family/src/exports/control.ts
Introduces EnumStorageKeyResolver and ContractToSchemaIROptions.resolveEnumStorageKey; contractToSchemaIR/deriveAnnotations normalize enum annotations and allow target-provided keying (falls back to nativeType).
Migration planning with namespace-qualified enums
packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts, packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
Planner uses namespace-local lookups (locateNamespaceTypeInStorage), enumRebuildCallRecipe accepts namespaceId and targets namespace DDL schema, nativeEnumPlanCallStrategy uses compound-keyed enum maps and tracks compound-key states to avoid invalid mixed introduce/rebuild plans, and collectPostgresEnumTypes returns compound-keyed maps.
Verify/planner wiring and runner updates
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts, packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts
verifySqlSchema is wired to use createResolveExistingEnumValues(contract.storage) for enum value resolution; planner/runner imports and calls updated accordingly; issue-planner targets per-namespace DDL schema when creating enum types.
Comprehensive test suite for namespace enum scenarios
packages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.ts, packages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.ts, packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
Adds tests for enum collisions across namespaces, per-namespace creation/add/rebuild/drop behavior, cross-namespace binding regression, and updates fixtures to include namespaceId and compound-keyed storage entries; adapter test updated to expect compound-keyed introspection keys.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant verifySchema
  participant verifySqlSchema
  participant PostgresAdapter
  participant Planner
  Client->>verifySchema: invoke verifySchema(contract)
  verifySchema->>verifySqlSchema: pass resolveExistingEnumValues (prefer contract-scoped)
  verifySqlSchema->>PostgresAdapter: resolveExistingEnumValues(schema, enumType, namespaceId)
  PostgresAdapter-->>verifySqlSchema: existing enum values (by schemaName+nativeType)
  verifySqlSchema->>Planner: emit issues with namespaceId
  Planner->>Planner: plan enum ops using compound-key (namespaceId + typeName)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A rabbit hops through namespaces bright,
Where enums now wear their location right,
Compound keys stitch each schema tight,
Collisions sorted by day and night,
Hooray for tidy enum flight! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: making Postgres enum planning namespace-aware, which directly addresses the collision issue documented in the objectives.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2686-s1e-namespace-aware-enum-planning

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented May 29, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/@prisma-next/extension-author-tools@632

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/@prisma-next/mongo-runtime@632

@prisma-next/family-mongo

npm i https://pkg.pr.new/@prisma-next/family-mongo@632

@prisma-next/sql-runtime

npm i https://pkg.pr.new/@prisma-next/sql-runtime@632

@prisma-next/family-sql

npm i https://pkg.pr.new/@prisma-next/family-sql@632

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/@prisma-next/extension-arktype-json@632

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/@prisma-next/extension-cipherstash@632

@prisma-next/middleware-cache

npm i https://pkg.pr.new/@prisma-next/middleware-cache@632

@prisma-next/mongo

npm i https://pkg.pr.new/@prisma-next/mongo@632

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/@prisma-next/extension-paradedb@632

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/@prisma-next/extension-pgvector@632

@prisma-next/extension-postgis

npm i https://pkg.pr.new/@prisma-next/extension-postgis@632

@prisma-next/postgres

npm i https://pkg.pr.new/@prisma-next/postgres@632

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/@prisma-next/sql-orm-client@632

@prisma-next/sqlite

npm i https://pkg.pr.new/@prisma-next/sqlite@632

@prisma-next/target-mongo

npm i https://pkg.pr.new/@prisma-next/target-mongo@632

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/@prisma-next/adapter-mongo@632

@prisma-next/driver-mongo

npm i https://pkg.pr.new/@prisma-next/driver-mongo@632

@prisma-next/contract

npm i https://pkg.pr.new/@prisma-next/contract@632

@prisma-next/utils

npm i https://pkg.pr.new/@prisma-next/utils@632

@prisma-next/config

npm i https://pkg.pr.new/@prisma-next/config@632

@prisma-next/errors

npm i https://pkg.pr.new/@prisma-next/errors@632

@prisma-next/framework-components

npm i https://pkg.pr.new/@prisma-next/framework-components@632

@prisma-next/operations

npm i https://pkg.pr.new/@prisma-next/operations@632

@prisma-next/ts-render

npm i https://pkg.pr.new/@prisma-next/ts-render@632

@prisma-next/contract-authoring

npm i https://pkg.pr.new/@prisma-next/contract-authoring@632

@prisma-next/ids

npm i https://pkg.pr.new/@prisma-next/ids@632

@prisma-next/psl-parser

npm i https://pkg.pr.new/@prisma-next/psl-parser@632

@prisma-next/psl-printer

npm i https://pkg.pr.new/@prisma-next/psl-printer@632

@prisma-next/cli

npm i https://pkg.pr.new/@prisma-next/cli@632

@prisma-next/cli-telemetry

npm i https://pkg.pr.new/@prisma-next/cli-telemetry@632

@prisma-next/emitter

npm i https://pkg.pr.new/@prisma-next/emitter@632

@prisma-next/migration-tools

npm i https://pkg.pr.new/@prisma-next/migration-tools@632

prisma-next

npm i https://pkg.pr.new/prisma-next@632

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/@prisma-next/vite-plugin-contract-emit@632

@prisma-next/mongo-codec

npm i https://pkg.pr.new/@prisma-next/mongo-codec@632

@prisma-next/mongo-contract

npm i https://pkg.pr.new/@prisma-next/mongo-contract@632

@prisma-next/mongo-value

npm i https://pkg.pr.new/@prisma-next/mongo-value@632

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/@prisma-next/mongo-contract-psl@632

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/@prisma-next/mongo-contract-ts@632

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/@prisma-next/mongo-emitter@632

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/@prisma-next/mongo-schema-ir@632

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/@prisma-next/mongo-query-ast@632

@prisma-next/mongo-orm

npm i https://pkg.pr.new/@prisma-next/mongo-orm@632

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/@prisma-next/mongo-query-builder@632

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/@prisma-next/mongo-lowering@632

@prisma-next/mongo-wire

npm i https://pkg.pr.new/@prisma-next/mongo-wire@632

@prisma-next/sql-contract

npm i https://pkg.pr.new/@prisma-next/sql-contract@632

@prisma-next/sql-errors

npm i https://pkg.pr.new/@prisma-next/sql-errors@632

@prisma-next/sql-operations

npm i https://pkg.pr.new/@prisma-next/sql-operations@632

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/@prisma-next/sql-schema-ir@632

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/@prisma-next/sql-contract-psl@632

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/@prisma-next/sql-contract-ts@632

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/@prisma-next/sql-contract-emitter@632

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/@prisma-next/sql-lane-query-builder@632

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/@prisma-next/sql-relational-core@632

@prisma-next/sql-builder

npm i https://pkg.pr.new/@prisma-next/sql-builder@632

@prisma-next/target-postgres

npm i https://pkg.pr.new/@prisma-next/target-postgres@632

@prisma-next/target-sqlite

npm i https://pkg.pr.new/@prisma-next/target-sqlite@632

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/@prisma-next/adapter-postgres@632

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/@prisma-next/adapter-sqlite@632

@prisma-next/driver-postgres

npm i https://pkg.pr.new/@prisma-next/driver-postgres@632

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/@prisma-next/driver-sqlite@632

commit: ed49074

@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 135.21 KB (+0.09% 🔺)
postgres / emit 124.97 KB (+0.07% 🔺)
mongo / no-emit 73.94 KB (0%)
mongo / emit 68.67 KB (0%)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts (1)

136-144: 💤 Low value

Bare as cast should use blindCast or castAs.

Per coding guidelines, the cast at line 143 should use blindCast with a reason string.

♻️ Suggested fix
+import { blindCast } from '`@prisma-next/utils/casts`';
+
 function locateNamespaceType(
   storage: SqlStorage,
   namespaceId: string,
   typeName: string,
 ): PostgresEnumStorageEntry | undefined {
   const ns = storage.namespaces[namespaceId];
   if (!ns || !('enum' in ns) || ns.enum == null) return undefined;
-  return (ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName];
+  return blindCast<Record<string, PostgresEnumStorageEntry>, 'namespace enum slot is untyped index-signature'>(ns.enum)[typeName];
 }

As per coding guidelines: "No bare as in production code. Use blindCast<T, "Reason"> or castAs<T> from @prisma-next/utils/casts."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts`
around lines 136 - 144, Replace the bare TypeScript `as` cast in
locateNamespaceType with the project's cast utility: use blindCast or castAs
from `@prisma-next/utils/casts`; specifically, where the code currently does
(ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName], wrap the value
with blindCast<Record<string, PostgresEnumStorageEntry>, "Describe reason
here">(ns.enum) (or use castAs<Record<string,
PostgresEnumStorageEntry>>(ns.enum)) and provide a short reason string
explaining why the blind cast is safe; update the import if needed and keep the
rest of locateNamespaceType (storage, namespaceId, typeName) unchanged.
packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts (1)

70-78: 💤 Low value

Bare as cast should use blindCast or castAs.

Per coding guidelines, production code should avoid bare as casts. The cast at line 77 should use blindCast from @prisma-next/utils/casts with a reason string explaining why the cast is necessary.

♻️ Suggested fix
+import { blindCast } from '`@prisma-next/utils/casts`';
+
 function locateNamespaceTypeInStorage(
   storage: SqlStorage,
   namespaceId: string,
   typeName: string,
 ): unknown {
   const ns = storage.namespaces[namespaceId];
   if (!ns || !('enum' in ns) || ns.enum == null) return undefined;
-  return (ns.enum as Record<string, unknown>)[typeName];
+  return blindCast<Record<string, unknown>, 'namespace enum slot is untyped index-signature'>(ns.enum)[typeName];
 }

As per coding guidelines: "No bare as in production code. Use blindCast<T, "Reason"> or castAs<T> from @prisma-next/utils/casts."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`
around lines 70 - 78, In locateNamespaceTypeInStorage replace the bare cast
"(ns.enum as Record<string, unknown>)[typeName]" with a safe cast using
blindCast from "`@prisma-next/utils/casts`" (import it) and provide a short reason
string explaining why we trust ns.enum shape (e.g., "enum shape validated
elsewhere"); ensure you call blindCast<Record<string, unknown>,
"Reason">(ns.enum) before indexing by typeName so no bare "as" remains.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts`:
- Around line 139-146: The enum collection logic (involving allStorageTypesMap
and namespaceIdForEnumType) uses the bare enum name key (k/typeName), causing
collisions when different namespaces define the same enum; change the keys to a
namespace-qualified form (e.g., `${nsId}:${k}`) when inserting into
allStorageTypesMap and namespaceIdForEnumType and update any lookups that use
typeName (including the similar block around lines 172-181) to use the same
qualified key so enums from different namespaces are stored and verified
separately.

---

Nitpick comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`:
- Around line 70-78: In locateNamespaceTypeInStorage replace the bare cast
"(ns.enum as Record<string, unknown>)[typeName]" with a safe cast using
blindCast from "`@prisma-next/utils/casts`" (import it) and provide a short reason
string explaining why we trust ns.enum shape (e.g., "enum shape validated
elsewhere"); ensure you call blindCast<Record<string, unknown>,
"Reason">(ns.enum) before indexing by typeName so no bare "as" remains.

In
`@packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts`:
- Around line 136-144: Replace the bare TypeScript `as` cast in
locateNamespaceType with the project's cast utility: use blindCast or castAs
from `@prisma-next/utils/casts`; specifically, where the code currently does
(ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName], wrap the value
with blindCast<Record<string, PostgresEnumStorageEntry>, "Describe reason
here">(ns.enum) (or use castAs<Record<string,
PostgresEnumStorageEntry>>(ns.enum)) and provide a short reason string
explaining why the blind cast is safe; update the import if needed and keep the
rest of locateNamespaceType (storage, namespaceId, typeName) unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: c1f2993c-54bd-474d-bf82-9a9bbeb2c89a

📥 Commits

Reviewing files that changed from the base of the PR and between ab6eaaa and 5dbd389.

⛔ Files ignored due to path filters (2)
  • projects/contract-ir-planes/slices/namespace-aware-enum-planning/plan.md is excluded by !projects/**
  • projects/contract-ir-planes/slices/namespace-aware-enum-planning/spec.md is excluded by !projects/**
📒 Files selected for processing (14)
  • packages/1-framework/1-core/framework-components/src/control/control-result-types.ts
  • packages/2-sql/9-family/src/core/control-adapter.ts
  • packages/2-sql/9-family/src/core/control-instance.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/enum-planning.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts
  • packages/3-targets/3-targets/postgres/src/exports/enum-planning.ts
  • packages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.ts`:
- Around line 336-337: The test currently only checks that a CreateEnumTypeCall
and a DropEnumTypeCall exist in the calls array; update the assertions to filter
for those call types and assert their schemaName is 'public' (e.g.,
calls.filter(c => c instanceof CreateEnumTypeCall) and check every
filteredCall.schemaName === 'public'), and likewise for DropEnumTypeCall; also
tighten the test by asserting expected counts (e.g., exact number of create and
drop calls) to prevent false positives from calls emitted for other schemas.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 867ec675-7964-41cc-a5c0-5f85806e8f79

📥 Commits

Reviewing files that changed from the base of the PR and between 5dbd389 and 284b2d0.

📒 Files selected for processing (5)
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/migrations/enum-collision.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts

@wmadden
wmadden force-pushed the tml-2686-s1e-namespace-aware-enum-planning branch from f6389fd to 20c3f82 Compare May 30, 2026 14:16
wmadden and others added 13 commits May 30, 2026 17:27
The replanned project plan runs S1.E parallel to S1.D (disjoint
surfaces; the planner bug pre-dates the project). The slice spec B1 and
plan D5 note still said "after S1.D" / "sequenced after S1.D for focus".
Reframe B1 as a parallel slice whose only ordering lever is reviewer
bandwidth, and update the PR-body sequencing note + Linear ref.

Signed-off-by: Will Madden <[email protected]>
…at all enum verifier sites

EnumValuesChangedIssue gains a required `namespaceId: string` field so the
downstream planner can match the issue to the correct namespace's enum without
re-scanning. The SQL family verifier's `verifyEnumType` now accepts and stamps
the namespace coordinate on both `type_missing` and `enum_values_changed` issues.
Existing tests updated to populate the field.

Signed-off-by: Will Madden <[email protected]>
…ordinate directly

Replace cross-namespace scan loops in locateNamespaceType (planner-strategies.ts)
and locateNamespaceTypeInStorage (issue-planner.ts) with direct reads keyed by
namespaceId. Both helpers now take (storage, namespaceId, typeName) and read
storage.namespaces[namespaceId]?.enum?.[typeName] directly — no first-match-wins
scan across all namespaces.

Thread the namespace coordinate through all three callsites:
- enumRebuildCallRecipe passes namespaceId (from outer loop) to locateNamespaceType
- mapIssueToCall passes resolveNamespaceIdForIssue(issue) to locateNamespaceTypeInStorage
- nativeEnumPlanCallStrategy uses a temporary scan loop (D3 will replace once
  collectPostgresEnumTypes returns compound-keyed entries)

Column-ref walk in enumRebuildCallRecipe narrowed by nsId === namespaceId so
columns in other namespaces sharing a typeRef name do not receive ALTER TYPE calls
intended for a different namespace's enum.

DDL schema resolution threaded via resolveDdlSchemaForNamespace(ctx, namespaceId)
at each CreateEnumTypeCall, AddEnumValuesCall, DropEnumTypeCall, and RenameTypeCall
site.

Signed-off-by: Will Madden <[email protected]>
…typeName)

D3a (planner-side compound key). collectPostgresEnumTypes now returns a map
keyed by the serialised compound key ${namespaceId}\u0000${typeName} instead of
bare typeName, so two namespaces declaring an enum with the same NAME produce two
distinct entries — no last-write-wins collapse. NUL is the separator (invalid in
both Postgres identifiers and TS symbol names, so unambiguous).

nativeEnumPlanCallStrategy iterates compound entries; handledKeys / introducedKeys
/ rebuiltKeys are compound-key sets. The issue-matching filter resolves the issue
to its compound key via enumCompoundKey(resolveNamespaceIdForIssue(issue),
issue.typeName), relying on the D1 substrate guarantee that enum-related issues
carry namespaceId. The introduce-and-rebuild guard error displays keys with a
readable "ns.type" rendering.

This closes the same-NAME collision (the primary CodeRabbit finding) and satisfies
SDoD6/SDoD7. The same-nativeType collision (readExistingEnumValues schema axis,
spec edge case #3) is deferred to D3b: threading (schemaName, nativeType) through
readExistingEnumValues cascades into the schema-IR provider (the introspection
merge in 6-adapters/.../control-adapter.ts explicitly discards all-but-first
namespace enum storage types), which the D3 refusal trigger routes to a separate
dispatch rather than expanding scope here.

Signed-off-by: Will Madden <[email protected]>
…on merge

Key live-schema enum lookup by (schemaName, nativeType) compound key. Merge per-schema storageTypes on multi-namespace introspection. Thread namespaceId through verifier resolveExistingEnumValues callback.

Signed-off-by: Will Madden <[email protected]>
Exercise introduce, add_values, rebuild, same-nativeType, and drop paths under audit/public Status collision. Pre-fix regression asserts two CreateEnumTypeCall against empty schema.

Signed-off-by: Will Madden <[email protected]>
The (schemaName, nativeType) enum lookup keyed the unbound namespace by its
__unbound__ DDL-emit sentinel, but introspection keys storageTypes by the live
current_schema() (public). The mismatch made the planner miss existing enums and
re-emit CreateEnumTypeCall, failing reconciliation/storage-types integration.

Resolve the read schema via resolveDdlSchemaForNamespaceStorage, which returns
annotations.pg.schema for the unbound coordinate. Centralise pg-annotation access
behind a typed readPgAnnotations helper using blindCast (clears lint:casts).
Fix issue-planner test fixture to key storageTypes by the live schema.

Signed-off-by: Will Madden <[email protected]>
…__ sentinel

CreateEnumTypeCall / AddEnumValuesCall and the rebuild recipe resolved the enum
type schema via resolveDdlSchemaForNamespace, which returns the __unbound__
DDL-emit sentinel for a pure-unbound contract — producing CREATE TYPE
"__unbound__"."X" that fails with schema does not exist. Route enum type DDL
through resolveDdlSchemaForNamespaceStorage so the unbound coordinate resolves to
the introspected current_schema (matching the read-lookup key and post-apply
verification); named namespaces are unchanged. Column-ref table qualification is
left on resolveDdlSchemaForNamespace as before.

Signed-off-by: Will Madden <[email protected]>
…lumn binding

Contract-to-contract migration planning (migration plan) projects the prior
contract to a schema IR via the family provider deriveAnnotations, which keyed
enum storageTypes by bare nativeType. The compound-keyed readExistingEnumValues
could not find them, so the planner took the introduce path instead of the
rebuild recipe.

deriveAnnotations now schema-qualifies namespace-scoped enum keys via an
injected EnumStorageKeyResolver. The Postgres DDL-schema resolution and the
compound-key format stay in target-postgres (control.ts wires the resolver from
resolveDdlSchemaForNamespaceStorage + enumStorageCompoundKey); the family layer
treats the returned string as opaque. Codec-typed storage types stay bare-keyed.
lint:deps stays green — no family to target import.

Also fix enumRebuildCallRecipe column-ref binding: a column carries a bare
typeRef whose enum may live in a different namespace (the builder places
contract-level types: enums in the default public namespace while a model table
sits in the unbound namespace). Resolve the column to its own-namespace enum
when present, else the ambient/public enum, replacing the over-narrow
nsId === namespaceId filter that dropped the alterColumnType migration.

Signed-off-by: Will Madden <[email protected]>
…lapse

The family verifier aggregated every namespace enum into a bare-name-keyed map
and ran verifyEnumType once per unique name, so two namespaces declaring the
same enum name collapsed last-write-wins and only one was verified. Verify
storage.types codec entries by name and namespace enums per (namespaceId,
typeName) instead, each carrying its own namespace coordinate. The bare-keyed
column typeRef resolution map (verifySchemaTables) is unchanged.

Addresses a CodeRabbit major finding. Adds a verifier regression test (two
namespaces, same enum name -> two distinct type_missing issues) and tightens the
cross-namespace rebuild test to assert schemaName + exact call counts.

Signed-off-by: Will Madden <[email protected]>
Use SqlStorage namespace indexing instead of Object.entries casts in
schema verify, and replace control-adapter blindCast with a runtime-
narrowed readPostgresSchemaIrAnnotations accessor exported from
target-postgres enum-planning.

Signed-off-by: wmadden-electric <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants