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

TML-2500 (M1): cross-contract FK carrier + aggregate-load checks - #745

Merged
wmadden merged 21 commits into
mainfrom
tml-2500-cross-contract-space-fk-references
Jun 7, 2026
Merged

wmadden merged 21 commits into
mainfrom
tml-2500-cross-contract-space-fk-references

Conversation

@wmadden

@wmadden wmadden commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

First slice (M1 — Foundation) of TML-2500, cross-contract-space FK references. It lands the storage-plane IR carrier and the aggregate-load-time validations. No authoring surface yet — the TS brand surface and PSL colon-prefix grammar are M2; planner/verifier wiring and the PGlite e2e are M3.

This is the substrate that lets an app contract reference a table owned by another contract space (the canonical case being Profile.user → supabase:auth.User).

What's in this PR

  • FK reference carrier — ForeignKeyReference carries an optional spaceId; its presence is the discriminator (absent ⇒ local, present ⇒ cross-space) — no separate tag field. A cross-space reference carries spaceId plus the full coordinate (namespace admitting the __unbound__ sentinel + table + column), so the target resolves without lexical context. Local FKs serialize byte-identically to before (NFR2). The ArkType schema rejects an unknown origin-style key; round-trip property test over a mix of local/cross-space carriers (AC8).
  • Cross-space dependency graph + cycle rejection — buildExtensionLoadOrder derives a load order from each pack's declared extensionPacks and rejects cycles at load time, naming the cycle members (FR12/FR13).
  • Namespace-ownership collisions — delivered by making main's existing disjointness integrity check namespace-aware (FR15/FR16). disjointness previously keyed on the bare entity name (elementCoordinates yields the full coordinate but it was discarded), so it would have false-positived on same-named tables in different namespaces across spaces — e.g. auth.users (supabase space) vs public.users (app space), the exact multi-namespace scenario this project enables. It now keys on (namespaceId, entityKind, entityName) and reports a readable namespace.name element. Two spaces declaring the same primitive fail load naming both contributors.
  • Reverse-reference rejection — a cross-space FK pointing against the dependency arrows (an extension referencing the app) fails load (FR14), wired in the SQL family where extension FKs are visible.

Reconciliation note: an earlier revision of this PR added a separate namespaceOwnershipCollision check; after merging latest main it turned out to duplicate disjointness. The redundant check was removed and disjointness (the incumbent, consumed by db-init/run/verify/migration-check) was fixed instead — one correct, namespace-aware ownership check.

M1 acceptance criteria: AC6 (collision + cycle), AC8 (round-trip), AC10 (lint:deps + cast ratchet clean). AC9 regression: targeted suites green; no TML-2459 local-FK test modified.

Design notes (v0.1 scope)

  • FR12 — listed-pack scope. The graph + cycle detection run over the packs the app lists, with edges from each pack's declared extensionPacks; a pack that declares a dependency on a space not in the set fails load with a clear "add it to extensionPacks" diagnostic. Transitive auto-loading of unlisted packs is deferred — it needs a spaceId → descriptor resolver that doesn't exist yet, and the canonical one-hop app → supabase case never needs it.
  • Runtime cross-space query/traversal is a Non-goal here. This slice delivers the FK purely as a database constraint (referential integrity + cascade), realised through migration/DDL. Direct cross-space querying and relation include would require a runtime contract-space aggregate (undesigned); deferred to a future project.

Validation

Targeted suites at HEAD, all green: @prisma-next/sql-contract 146, @prisma-next/framework-components 349, @prisma-next/family-sql 334, @prisma-next/migration-tools 548. pnpm typecheck, pnpm lint:deps, and pnpm lint:casts (delta=0) all clean. One pre-existing @prisma-next/adapter-sqlite Turbo-cascade typecheck artifact (present on main, unrelated).

Walking skeleton

The examples/supabase walking skeleton (landed on main) composes the app space + the @prisma-next/supabase extension space and runs db init / db verify through the now-reconciled integrity checks. M1's obligation is that it stays green against these checks. The headline Profile.userId → auth.User.id cross-contract FK + cascade-delete step is deferred to M2 (authoring surface) + M3 (planner/verifier) — it cannot be authored at M1's foundation level.

Scope discipline

Storage-plane IR + aggregate-load validation only — no authoring DSL, planner, verifier, or Mongo changes. Those land in M2/M3.

Refs TML-2500.

🤖 Generated with Claude Code

@wmadden
wmadden requested a review from a team as a code owner June 6, 2026 14:26
@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

Adds extension dependency ordering and namespace ownership collision detection; represents cross-space foreign keys with optional spaceId, updates validators and tests; adds runtime check rejecting cross-space FKs that point against declared extension dependencies; integrates collision reporting into migration integrity and CLI failure mapping.

Changes

Cross-Space Foreign Keys with Dependency and Collision Validation

Layer / File(s) Summary
Extension dependency ordering and namespace collision detection
packages/1-framework/1-core/framework-components/src/control/control-stack.ts, packages/1-framework/1-core/framework-components/src/exports/control.ts, packages/1-framework/1-core/framework-components/test/control-stack.test.ts
Adds readDeclaredDependencyIds, buildExtensionLoadOrder (Kahn topological sort with missing-dependency and cycle detection), findNamespaceOwnershipCollisions scanning storage views for duplicate (namespaceId, entityKind, name) primitives, integrates load-order call into createControlStack, and adds re-exports and tests.
Integrity computation and CLI mapping for collisions
packages/1-framework/3-tooling/migration/src/aggregate/check-integrity.ts, packages/1-framework/3-tooling/migration/src/integrity-violation.ts, packages/1-framework/3-tooling/migration/test/aggregate/check-integrity.test.ts, packages/1-framework/3-tooling/cli/src/commands/migration-check.ts, packages/1-framework/3-tooling/cli/src/utils/integrity-violation-to-check-failure.ts
Extends IntegrityViolation with namespaceOwnershipCollision, computes collisions when checkContracts is enabled by calling findNamespaceOwnershipCollisions, adds tests, maps collisions to PN-MIG-CHECK-017, and excludes collisions from space-scoped migration-check output.
ForeignKeyReference IR and validator updates
packages/2-sql/1-core/contract/src/ir/foreign-key-reference.ts, packages/2-sql/1-core/contract/src/validators.ts, packages/2-sql/1-core/contract/test/foreign-key-cross-space.test.ts
Adds optional spaceId to ForeignKeyReferenceInput and ForeignKeyReference, introduces ForeignKeySourceSchema, updates ArkType schemas to include spaceId, conditions cross-namespace target resolution to skip when spaceId is present, and adds comprehensive tests for local vs cross-space serialization, schema validation, and storage validation behavior.
Cross-space FK reverse-reference validation
packages/2-sql/9-family/src/core/control-instance.ts, packages/2-sql/9-family/test/cross-contract-validation.test.ts
Adds assertNoCrossSpaceFkReverseReferences to build a transitive extension dependency map and reject cross-space FKs whose target space depends on the FK owner; wired into createSqlFamilyInstance; tests validate acceptance and rejection cases and diagnostic messaging.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • prisma/prisma-next#741: Modifies CLI migration-check failure pipeline and failure schemas which intersect with this PR's migration-check/CheckFailure mapping.
  • prisma/prisma-next#626: Related migration integrity and computeIntegrityViolations changes that this PR extends with namespaceOwnershipCollision reporting.

Suggested reviewers

  • aqrln

Poem

🐰 I hop through namespaces, tidy and spry,

ordering packs so collisions say goodbye.
Cross-space keys check direction before they bind,
no reverse references that tangle or wind.
A rabbit’s quick audit — neat, well-defined.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% 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
Title check ✅ Passed The title 'TML-2500 (M1): cross-contract FK carrier + aggregate-load checks' clearly describes the two main changes in the PR: enabling cross-contract foreign-key references and implementing aggregate-load validation checks.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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-2500-cross-contract-space-fk-references

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

@pkg-pr-new

pkg-pr-new Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-supabase@745

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 4a70ecd

@github-actions

github-actions Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 145.45 KB (0%)
postgres / emit 117.12 KB (0%)
mongo / no-emit 76.09 KB (0%)
mongo / emit 70.95 KB (0%)
cf-worker / no-emit 175.1 KB (0%)
cf-worker / emit 143.5 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

🤖 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/1-framework/1-core/framework-components/src/control/control-stack.ts`:
- Around line 526-528: The call to buildExtensionLoadOrder(extensionPacks) is
only validating but its result isn't used, so allDescriptors (and subsequent
assembly) still uses the original extensionPacks order; update the code to
capture and use the computed ordered list (e.g., const orderedExtensionPacks =
buildExtensionLoadOrder(extensionPacks) or overwrite extensionPacks) and then
build allDescriptors from that ordered list (use orderedExtensionPacks in place
of extensionPacks) so dependency-respecting ordering is applied during control
stack assembly.
🪄 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: 3c723d7f-9e0e-454a-b622-a9dadd95ce63

📥 Commits

Reviewing files that changed from the base of the PR and between d6f3968 and f6b53ba.

⛔ Files ignored due to path filters (4)
  • projects/cross-contract-refs/plan.md is excluded by !projects/**
  • projects/cross-contract-refs/rollups/2026-06-05-opening.md is excluded by !projects/**
  • projects/cross-contract-refs/slices/M1/plan.md is excluded by !projects/**
  • projects/cross-contract-refs/spec.md is excluded by !projects/**
📒 Files selected for processing (13)
  • packages/1-framework/1-core/framework-components/src/control/control-stack.ts
  • packages/1-framework/1-core/framework-components/src/exports/control.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/utils/integrity-violation-to-check-failure.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/check-integrity.ts
  • packages/1-framework/3-tooling/migration/src/integrity-violation.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/check-integrity.test.ts
  • packages/2-sql/1-core/contract/src/ir/foreign-key-reference.ts
  • packages/2-sql/1-core/contract/src/validators.ts
  • packages/2-sql/1-core/contract/test/foreign-key-cross-space.test.ts
  • packages/2-sql/9-family/src/core/control-instance.ts
  • packages/2-sql/9-family/test/cross-contract-validation.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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/2-sql/1-core/contract/src/validators.ts (1)

156-158: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject spaceId on FK sources.

Line 157 reuses ForeignKeyReferenceSchema for source, so structural validation now accepts { source: { ..., spaceId } } even though the owning table is always local. validateSqlStorageConsistency() never rejects that extra coordinate, and the duplicate-definition signature later in this file hashes source verbatim, so malformed and canonical versions of the same FK can slip through as distinct entries.

Suggested fix
+const LocalForeignKeyReferenceSchema = type({
+  '+': 'reject',
+  namespaceId: 'string',
+  tableName: 'string',
+  columns: type.string.array().readonly(),
+}) satisfies Type<ForeignKeyReferenceInput>;
+
 export const ForeignKeySchema = type({
-  source: ForeignKeyReferenceSchema,
+  source: LocalForeignKeyReferenceSchema,
   target: ForeignKeyReferenceSchema,
   'name?': 'string',
   'onDelete?': ReferentialActionSchema,
   'onUpdate?': ReferentialActionSchema,
   constraint: 'boolean',
   index: 'boolean',
 }) satisfies Type<ForeignKeyInput>;
🤖 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/2-sql/1-core/contract/src/validators.ts` around lines 156 - 158,
ForeignKeySchema currently reuses ForeignKeyReferenceSchema for source which
allows a spaceId on FK sources; change the source to a schema that forbids/omits
spaceId (e.g., create ForeignKeySourceSchema or use an omit/refine of
ForeignKeyReferenceSchema that rejects spaceId) and update anywhere using
ForeignKeySchema (including validateSqlStorageConsistency() and the
duplicate-definition hashing logic) so the source is validated/hashed without a
spaceId coordinate.
🤖 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.

Outside diff comments:
In `@packages/2-sql/1-core/contract/src/validators.ts`:
- Around line 156-158: ForeignKeySchema currently reuses
ForeignKeyReferenceSchema for source which allows a spaceId on FK sources;
change the source to a schema that forbids/omits spaceId (e.g., create
ForeignKeySourceSchema or use an omit/refine of ForeignKeyReferenceSchema that
rejects spaceId) and update anywhere using ForeignKeySchema (including
validateSqlStorageConsistency() and the duplicate-definition hashing logic) so
the source is validated/hashed without a spaceId coordinate.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 09561a8d-aa5e-4098-b781-3f1ce4e61d2d

📥 Commits

Reviewing files that changed from the base of the PR and between f6b53ba and bdb1fed.

⛔ Files ignored due to path filters (1)
  • projects/cross-contract-refs/slices/M1/plan.md is excluded by !projects/**
📒 Files selected for processing (5)
  • packages/2-sql/1-core/contract/src/ir/foreign-key-reference.ts
  • packages/2-sql/1-core/contract/src/validators.ts
  • packages/2-sql/1-core/contract/test/foreign-key-cross-space.test.ts
  • packages/2-sql/9-family/src/core/control-instance.ts
  • packages/2-sql/9-family/test/cross-contract-validation.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/2-sql/9-family/src/core/control-instance.ts
  • packages/2-sql/9-family/test/cross-contract-validation.test.ts
  • packages/2-sql/1-core/contract/test/foreign-key-cross-space.test.ts

@wmadden

wmadden commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

Done (A-002). Introduced ForeignKeySourceSchema in validators.ts — a '+': 'reject' ArkType schema with only namespaceId, tableName, and columns (no spaceId). Updated ForeignKeySchema.source to use it; target keeps the full ForeignKeyReferenceSchema (spaceId permitted). Added tests: source with spaceId is rejected, target with spaceId is still accepted, local and cross-space cases pass. Commit: 028d7ea

wmadden and others added 21 commits June 7, 2026 11:14
…cision

Planning + design artifacts for cross-contract-space FK references:
- reconcile spec/plan against the now-landed TML-2459/TML-2493 substrate
- record Option B (declared, non-navigable cross-space relations)
- defer runtime cross-space query/traversal to a future project (Non-goals)
- add M1 dispatch decomposition + opening health rollup

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Extend ForeignKeyReference with an optional origin/'space' discriminator
so an FK target can identify a cross-contract-space reference:

- origin absent or 'local': local reference (same contract-space). No
  change to JSON shape — backward-compatible with all existing contracts.
- origin: 'space' + spaceId: string: cross-space reference. Both fields
  appear in JSON so round-trips are lossless.

ForeignKeyReferenceInput becomes a discriminated union of
LocalForeignKeyReferenceInput | SpaceForeignKeyReferenceInput.

ForeignKeyReferenceSchema is updated to match: a union of the two
shapes. ForeignKeySchema drops the type.declare<ForeignKeyInput>()
wrapper (incompatible with union-typed property schemas in ArkType).

validateSqlStorageConsistency skips the target-namespace table-existence
check for cross-space FKs (the referenced table lives in a foreign
contract-space, not in this contract's storage).

No authoring DSL, domain plane, or planner/verifier changes — storage
plane and IR only.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add import of ForeignKeyReferenceInput and ForeignKeyInput from ./types,
and apply `satisfies Type<T>` guards to ForeignKeyReferenceSchema and
ForeignKeySchema. Both guards compile successfully — ArkType's union
output type for the discriminated .or() is assignable to the TypeScript
input union, so no comment is needed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tract aggregate

Add buildExtensionLoadOrder() to framework-components/control-stack.ts.
The function performs a Kahn topological sort over extension descriptors,
reading each descriptor's contractSpace.contractJson.extensionPacks via
structural duck-typing to discover declared dependencies (including
transitive ones from extensions that themselves declare extensionPacks).

A cycle throws with an error message that names every member of the cycle
(FR12/FR13). The check runs inside createControlStack() so it fires at
stack-assembly time for all families that use the framework stack.

buildExtensionLoadOrder is exported from @prisma-next/framework-components/control
so callers can invoke it independently.

Tests cover: empty input, single extension, linear A→B→C chain,
multi-dependency, transitive discovery, 2-cycle, 3-cycle, extensions
without contractSpace, and createControlStack end-to-end cycle rejection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…bare cast

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ection at aggregate load

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…e integrity check

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…orphan

Extract `findNamespaceOwnershipCollisions` as the canonical pure detector in
framework-components (control-stack.ts + exports/control barrel). Remove the
dead throwing `assertNoNamespaceOwnershipCollisions` wrapper, repoint its unit
tests to the pure function. Wire migration-tools check-integrity.ts to call
the shared detector, eliminating the duplicated algorithm.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ice plan

Captures the round-2/3 decisions: dependency-graph + cycle detection run over
the listed pack set (error on an unlisted declared dependency; transitive
auto-loading deferred), and the namespace-ownership collision check lands at
the migration-tools aggregate integrity layer (where the app contract is
available), while reverse-reference rejection stays in the SQL family.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…e on spaceId presence

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ce plan

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
buildExtensionLoadOrder returned the dependency-sorted IDs but the
caller discarded them, so allDescriptors and the returned extensionPacks
were assembled in original input order. Capture the ordered ID list,
map it back to descriptors, and use the ordered packs throughout.

A test asserts that when a dependent pack is listed before its
dependency in the input, the assembled stack has them in dependency
order.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
ForeignKeySchema.source was reusing ForeignKeyReferenceSchema which
permits spaceId. An FK source is always the owning (local) table and
must never carry spaceId. Introduce ForeignKeySourceSchema with
'+': 'reject' and no spaceId field, and use it for source. Target
keeps ForeignKeyReferenceSchema (spaceId legitimately permitted there).

Tests assert: source carrying spaceId is rejected, target carrying
spaceId is still accepted, local + cross-space cases pass unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…omments/tests

Removed (NFR2) from ForeignKeyReferenceInput JSDoc, (NFR2) section header
and describe label in foreign-key-cross-space.test.ts, (AC8) describe label
in the same file, (FR14, AC6) section comment in cross-contract-validation.test.ts,
and (FR15/FR16, AC6 collision half) section comment in control-stack.test.ts.
Kept all explanatory prose; only the transient label tokens were removed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
ForeignKeySchema now uses type.declare<ForeignKeyInput>().type({...})
instead of a bare type({...}) satisfies cast. ForeignKeyReferenceSchema
and ForeignKeySourceSchema keep satisfies because they include
'+': 'reject' — a meta-key ArkType's .declare<T> constraint rejects
when T has no '+' property. This is the same limitation that prevented
.declare on those schemas before M1.4; the source type would need a '+'
index signature to allow it, which would widen the contract type.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ure envelope

origin/main (TML-2836) renamed CheckFailure.pnCode -> code and added a space field. Update the namespaceOwnershipCollision case to the new shape (space: "app", code: ...), matching the sibling cross-space disjointness case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ullAssertion)

buildExtensionLoadOrder and findNamespaceOwnershipCollisions used queue.shift()! and collisions.get(key)!; restructured to a guarded shift and an entries() walk so biome check --error-on-warnings passes. Behavior unchanged (framework-components 350 + migration-tools 548 green).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…load order

Applying buildExtensionLoadOrder (review fix A-001) composes extension codec types in dependency/alphabetical order, so CodecTypes is now PgTypes & ArktypeJsonTypes & PgVectorTypes. Regenerated via pnpm fixtures:emit (not hand-edited).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ying)

Key on ${namespaceId}:${entityKind}:${entityName} so auth.users and
public.users are distinct; element is now the readable qualified form
e.g. public.users. Remove the redundant namespaceOwnershipCollision
violation kind and its helpers (findNamespaceOwnershipCollisions,
PN-MIG-CHECK-017) now that disjointness covers the same ground correctly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…to disjointness

Remove the findNamespaceOwnershipCollisions describe block from
control-stack.test.ts and replace the namespaceOwnershipCollision
describe block in check-integrity.test.ts with disjointness tests,
including a no-false-positive case (same name in different namespaces
→ no violation) and a true-collision case (same coordinate → one
violation with qualified element like public.users).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tion

Record Decision D-recon (fix disjointness namespace-awareness, remove namespaceOwnershipCollision) and the walking-skeleton obligation (FK deferred to M2/M3).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden force-pushed the tml-2500-cross-contract-space-fk-references branch from 4a70ecd to 7d5ecac Compare June 7, 2026 09:14
@wmadden
wmadden merged commit d869089 into main Jun 7, 2026
11 checks passed
@wmadden
wmadden deleted the tml-2500-cross-contract-space-fk-references branch June 7, 2026 09:14
wmadden-electric added a commit that referenced this pull request Jun 8, 2026
… 1 — read side) (#753)

## At a glance

Slice 1 of 4 of **[Target-contributed top-level PSL
blocks](https://linear.app/prisma-company/issue/TML-2804)** — the **read
side** of the declarative SPI. After this, an extension describes a new
top-level PSL block **as data** (a descriptor of its keyword, name, and
typed parameters), and the framework **parses, validates, and lowers it
to contract IR** with one generic interpreter. No extension-supplied
parse/print code runs.

This supersedes the function-based SPI built on
[#718](#718) (now draft): that
cut had each extension ship imperative `parser`/`printer` functions. The
mechanism is cherry-picked here; the functions are replaced by the
descriptor + generic interpreter. Rationale + design are in
`projects/target-contributed-psl-blocks/spec.md` (landed via #749).

```prisma
namespace public {
  model Profile { id String @id  userId String @unique }

  policy_select profiles_select_anon {
    target = Profile               // ref (same-namespace)
    as     = permissive            // option: permissive | restrictive
    roles  = [anon, authenticated] // list of ref (cross-space)
    using  = "auth.uid() = user_id"// value (codec-typed)
  }
}
```

The framework never learns the `policy_select` keyword directly — the
descriptor is data.

## What's in this PR

The parameter value-kind vocabulary and the generic read pipeline, built
across seven dispatches:

- **Declarative descriptor + vocabulary** (`framework-components`) —
`AuthoringPslBlockDescriptor` is data: keyword, discriminator, `name`,
and a `parameters` map of the four-kind union `PslBlockParam`: **`ref`**
(resolves to a declared entity; `refKind` + `scope`), **`value`**
(codec-typed), **`option`** (a closed set of allowed literal tokens — an
authoring constraint, *not* a domain enum), **`list`** (combinator). No
`parser`/`printer` fields. Plus the uniform parsed-node base (`{ kind,
name, parameters, span }`) and the `PslNamespace.extensionBlocks` slot.
- **Codec-typed `value` via the codec's existing `decodeJson`** — a
`value` literal is interpreted as JSON through the codec the parameter
declares: `codecLookup.get(codecId).decodeJson(JSON.parse(raw))` — the
same path that decodes literal column defaults. There is no bespoke PSL
codec hook; PSL literals are handled generically and codecs already own
value↔JSON, so `value` rides that existing medium (and gets full codec
expressiveness + correct JSON escaping for free). (`@default`'s legacy
literal handling is untouched — separate, future work.)
- **Generic parser** (`psl-parser`) — on an unknown top-level keyword,
the parser reads any declared block into the uniform node, capturing
each parameter's RHS by its declared kind. Built-in keywords stay
framework-parsed; an unregistered keyword still gets the clean
unknown-keyword diagnostic.
- **Generic validator + `ref` resolution** — reports (with spans)
unknown / missing-required parameters, `option`-not-in-set,
codec-rejected `value`, and `ref` unresolved within its scope
(`same-namespace`/`same-space` resolved against the parsed namespaces;
`cross-space` is a documented pass-through per the spec's first-consumer
allowance, leaning on the merged #745 coordinate model). A small
`PSL_EXTENSION_*` diagnostic taxonomy.
- **Load-time validation** — `assembleAuthoringContributions` rejects
duplicate keyword, duplicate discriminator (within `pslBlocks` and
within `entityTypes`), a `pslBlocks` descriptor with no matching
`entityTypes` factory, and a malformed descriptor. Standalone
`entityTypes` factories stay allowed.
- **Lowering + fixture + round-trip** — the uniform node lowers to IR
via the matching `entityTypes` factory; a test-only declarative
`policy_select` fixture round-trips **parse → validate → lower → IR**.

## A design decision worth a look

Validation runs **inside `parsePslDocument`** whenever `pslBlocks` are
registered, joining the parser's existing diagnostics. A `value`
parameter is validated by parsing its literal as JSON and running the
codec's existing `decodeJson`
(`codecLookup.get(codecId).decodeJson(JSON.parse(raw))`); malformed JSON
or a codec rejection surfaces a diagnostic. No production caller passes
`pslBlocks` yet — this is the read-side seam.

## Out of scope (later slices)

- **Generic printer + `contract infer`** — Slice 2,
[TML-2854](https://linear.app/prisma-company/issue/TML-2854). This PR's
round-trip stops at the lowered IR.
- **`PslNamespace` → ADR 224 `entries` migration** — Slice 3,
[TML-2849](https://linear.app/prisma-company/issue/TML-2849).
- **ADR 126 revision + three-layer ADR + close-out** — Slice 4,
[TML-2806](https://linear.app/prisma-company/issue/TML-2806).
- A `number` value-kind / field-declaration block bodies (deferred to
first consumer); real RLS (downstream).

## Relationships

- **[#718](#718 —
superseded function-SPI cut; draft; mechanism cherry-picked; branch
preserved.
- **[#745](#745) / TML-2500**
— merged; `ref` `cross-space` scope builds on its coordinate model. Not
a blocker.
- **[#748](#748) /
enums-as-domain** — independent; `option` is not an enum, `value` uses
ordinary scalar codecs.

## Verification

| Gate | Result |
|---|---|
| `pnpm typecheck` (the four touched packages) | clean |
| `pnpm test:packages` (psl-parser / psl-printer / framework-components
/ cli, in isolation) | pass — 100 / 34 / 395 / 1316 |
| `pnpm lint:deps` | clean |
| `pnpm lint:casts` | `delta=0` (no regression) |

A monorepo-wide typecheck has pre-existing, unrelated worktree
dist-not-built failures (migration-tools / mongo-contract /
sql-schema-ir / emitter / mongo-lowering) — none introduced here;
per-package typechecks for the touched packages are clean, and the
changes don't alter a public export signature those packages consume.

## Follow-ups recorded for downstream (not this slice)

- `ref-kind` vs `discriminator` mismatch for a non-`cross-space` ref to
an extension-contributed entity (the first RLS-roles-style consumer must
map `refKind` → discriminator).
- Duplicate-*keyword-string* across different namespace keys isn't
caught at assembly (duplicate-*path* is); harden in the keyword-dispatch
index if it matters.

Refs [TML-2804](https://linear.app/prisma-company/issue/TML-2804).

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Support for PSL extension blocks: parsing, validation, diagnostics,
namespace-aware reference resolution, and codec-backed value checks.
* Authoring API expanded so contributors can declare/register
extension-block descriptors that integrate into parse/validation and
cross-registry consistency checks.

* **Tests**
* Extensive unit and round‑trip tests and fixtures covering parsing,
validation, diagnostics, lowering, and reference/codec behaviors.

* **Chores**
* Test fixtures and tooling adjusted to include the new authoring
contributions shape.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Will Madden <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
wmadden-electric added a commit that referenced this pull request Jun 8, 2026
…orkspace (TML-2500 M4) (#770)

This is the documentation + close-out milestone (M4) for the
cross-contract-refs project. All four implementation milestones have
merged — M1 #745, M2 #752, M3a #756, M3b #765 — shipping
cross-contract-space foreign-key references end-to-end. This PR migrates
the project's durable knowledge into the canonical doc surfaces, records
the project as shipped in the umbrella tracker, lands the final-retro
lessons, and deletes the transient project workspace.

## What shipped (recap, for the reader without context)

An app contract can now declare a foreign key from a local model to a
model owned by an *extension's* contract space. The headline example,
live in `examples/supabase`:

```prisma
types {
  Uuid = String @db.Uuid
}

namespace public {
  model Profile {
    id     String @id @default(uuid())
    userId Uuid   @unique
    user   supabase:auth.AuthUser @relation(fields: [userId], references: [id], onDelete: Cascade)
    @@Map("profile")
  }
}
```

The planner lowers this to a real Postgres FK (`REFERENCES
"auth"."users"("id") ON DELETE CASCADE`), and a hermetic integration
test proves the cascade fires against a live database.

## Where the knowledge landed (M4.1)

The design knowledge that lived in the transient
`projects/cross-contract-refs/` workspace migrated to three canonical,
self-contained surfaces:

- **Subsystem doc** — a new "Cross-contract FK references" subsection in
`docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md`
(the extension hub). Records the *current shape*: the presence-based
optional `spaceId` discriminator on `ForeignKeyReference`,
dependency-graph construction, namespace-ownership rules, the
aggregate-loader resolution rule, and the `__unbound__`
DDL-qualification consequence.
- **ADR 226** — `docs/architecture docs/adrs/ADR 226 - Cross-contract
foreign-key references.md`. Records the *decisions*: presence-based
discrimination (chosen so local-FK JSON stays byte-identical), implicit
`extensionPacks` resolution, the DAG + reverse-reference rejection,
namespace ownership, Option-B non-navigable relations, the colon-prefix
PSL grammar, and no-diagnostic cascade. Cross-links ADR 212 / 221 / 225.
- **Authoring rulecard** —
`.agents/rules/cross-contract-fk-authoring.mdc`. The actionable Do/Don't
for authoring a cross-contract FK, including the hard-won M3b lesson
that the FK source column must match the target's native type (`types {
Uuid = String @db.Uuid }`), and that `@db.X` is type-constructor syntax
(only valid inside a `types {}` block), not a field attribute.

## Bookkeeping (M4.2)

- The umbrella tracker (`projects/supabase-integration/README.md`)
status row flipped to ✅ **Done & closed** with the four PR links, and
its link repointed from the (now-deleted) project spec to the durable
subsystem doc.
- The one durable dangling link —
`packages/3-extensions/supabase/README.md` pointing into the project dir
— repointed to ADR 226 / the subsystem doc.

## Final retro (M4.3)

Per the mandatory-final-retro invariant, the process lessons from this
project's execution landed in durable `drive/` calibration surfaces:

- `drive/spec/README.md` — spec illustrative snippets (PSL grammar, IR
shapes) must be re-verified against shipped code before execution, not
copied as fact. (This project hit it four times.)
- `drive/calibration/model-tier.md` — a worked example confirming the
existing "pin the dispatch tier explicitly, don't inherit" rule.
- `drive/calibration/dod.md` — test-dispatch briefs need a "claims
preserved" acceptance criterion: state what the test proves, on the
right surface.

## Definition of Done — verified

| AC | Status | Evidence |
|----|--------|----------|
| AC1 (TS cross-contract ref, non-navigable) | ✅ | M2 #752 |
| AC2 (PSL cross-contract ref, round-trip) | ✅ | M2 #752 + M3a #756 |
| AC3 (`__unbound__` unqualified REFERENCES) | ✅ | M3a #756 |
| AC4 (cascade permitted, DDL has ON DELETE CASCADE) | ✅ | M2 #752 + M3b
#765 |
| AC5 (missing-pack diagnostic, both surfaces) | ✅ | M2 #752 |
| AC6 (primitive collision + cycle rejection) | ✅ | M1 #745 |
| AC7 (live FK in `pg_constraint`, verifier clean) | ✅ | M3a #756 + M3b
#765 |
| AC8 (round-trip property test) | ✅ | M1 #745 |
| AC9 (TML-2459 local FK tests unchanged) | ✅ | all milestones |
| AC10 (`pnpm lint:deps` clean) | ✅ | all milestones |

All slices merged; mandatory final retro complete; durable docs landed;
no open ADRs blocking.

## Deletion

`projects/cross-contract-refs/` is removed. Verified before deletion:
trace integrity passes (89 events, 9 dispatches, all round/dispatch
pairs matched); no durable file (`packages/`, `examples/`, `docs/`,
`.agents/`) references the deleted path; `pnpm build` + `pnpm typecheck`
unaffected (nothing imports from `projects/`). References to
cross-contract-refs that remain in *other* project workspaces
(`supabase-integration`, `postgres-rls`, etc.) are
transient-to-transient and get cleaned at those projects' own
close-outs.

## Validation

- `pnpm typecheck`: 138/138
- `pnpm lint`: 79/79
- `pnpm lint:rules:symlinks`: clean (the new rulecard wired)
- `pnpm build`: clean

Refs: TML-2500.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Added comprehensive guidance for cross-contract foreign-key
references, including authoring conventions and architectural design
decisions.
* Updated ecosystem extensions documentation with cross-contract
reference patterns and resolution behavior.
* Enhanced calibration and code verification documentation with improved
guidance for test authoring and snippet validation.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Will Madden <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[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.

1 participant