Repository navigation
examples/supabase: cross-contract FK with cascade, end-to-end (TML-2500 M3b) - #765
Conversation
|
Warning Review limit reached
More reviews will be available in 56 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (3)
📒 Files selected for processing (41)
📝 WalkthroughWalkthroughRefactor to accept omitted/empty codec ChangesOptional typeParams throughout SQL contract system
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
5df1be8 to
75ce231
Compare
| const rows = await insertAndReadProfile(runtime, 'alice', userId); | ||
| expect(rows).toHaveLength(1); | ||
| expect(rows[0]).toMatchObject({ username: 'alice' }); | ||
| expect(rows[0]).toMatchObject({ username: 'alice', userId }); |
There was a problem hiding this comment.
What does this prove exactly? If the FK were not present, this would work identically.
There was a problem hiding this comment.
Addressed in 3935665: the cascade test was refactored to use raw SQL against auth.users (the foreign source) and the ORM for public.Profile (the FK owner). The test now exercises the FK constraint directly — deleting an auth.users row causes the cascade to delete the referencing Profile row, which is what proves the FK is in place.
| const afterDelete = await pg.query<{ count: string }>( | ||
| 'SELECT COUNT(*)::text AS count FROM public.profile WHERE "userId" = $1', | ||
| [userId], | ||
| ); |
There was a problem hiding this comment.
You should be using the ORM for this and all the preceding queries that operate on the public.Profile model
There was a problem hiding this comment.
Addressed in 3935665: all public.Profile operations now use the ORM client. Raw SQL is only used for auth.users operations, which don't have a contract in this space.
| readonly nativeType: string; | ||
| readonly typeParams: Record<string, unknown>; | ||
| readonly typeParams?: Record<string, unknown>; |
There was a problem hiding this comment.
Why did you make this optional? I thought the whole idea in our strategy was that this would always be present, and that the canonicalizer and serializer would ensure an empty value is represented consistently as {}?
There was a problem hiding this comment.
Addressed in 3935665: typeParams is optional on the input interface (StorageTypeInstanceInput) so callers that omit it at construction don't need to pass {}. The output type (StorageTypeInstance) still requires typeParams: Record<string, unknown> — always present. The toStorageTypeInstance helper normalises a missing value to {} at construction time. The canonicalizer and serializer continue to handle the canonical form; this change only relaxes what callers must supply when building inputs.
346e668 to
1d0056a
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/4-lanes/relational-core/src/codec-ref-for-column.ts`:
- Around line 65-74: The code currently treats any value with zero Object.keys
(including arrays like []) as "no typeParams" and drops them; change the
presence check so arrays are treated as present even if empty. Update the
hasParamKeys logic in codec-ref-for-column.ts (the instanceParams/hasParamKeys
check used when building the CodecRef) to: hasParamKeys = instanceParams !==
undefined && (Array.isArray(instanceParams) ||
Object.keys(instanceParams).length > 0) (or use an equivalent plain-object
check), and apply the same change to the second occurrence around lines 78-79 so
empty arrays are preserved as explicit typeParams while only canonicalizing
truly empty plain objects.
In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 476-491: The code currently treats any non-array object and
missing typeParams as equivalent; change the logic so only a plain empty object
({}) or undefined/null are treated as "missing" and everything else (arrays,
primitives, objects with prototypes, or objects with keys) counts as an explicit
payload. Replace the refHasTypeParamKeys computation with an explicit
isEmptyPlainObject check (e.g. typeof refTypeParams === 'object' &&
!Array.isArray(refTypeParams) && Object.getPrototypeOf(refTypeParams) ===
Object.prototype && Object.keys(refTypeParams).length === 0) and then treat
missing if refTypeParams is undefined/null or isEmptyPlainObject; keep the
runtime check that throws RUNTIME.CODEC_PARAMETERIZATION_MISMATCH when
descriptor.isParameterized is false but the ref is not missing (i.e. has an
explicit payload). Ensure you update references to refTypeParams,
refHasTypeParamKeys and the if that uses descriptor.isParameterized accordingly.
🪄 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: 8b957f72-95d3-4412-bd40-1ecc36490263
⛔ Files ignored due to path filters (3)
projects/cross-contract-refs/slices/M3b/plan.mdis excluded by!projects/**projects/cross-contract-refs/slices/M3b/spec.mdis excluded by!projects/**projects/cross-contract-refs/trace.jsonlis excluded by!projects/**
📒 Files selected for processing (39)
examples/supabase/src/contract.d.tsexamples/supabase/src/contract.jsonexamples/supabase/src/contract.prismaexamples/supabase/src/handlers.tsexamples/supabase/test/skeleton.integration.test.tspackages/1-framework/0-foundation/contract/test/canonicalization-path-match.test.tspackages/1-framework/0-foundation/contract/test/canonicalization.test.tspackages/1-framework/3-tooling/emitter/test/canonicalization.test.tspackages/1-framework/3-tooling/emitter/test/utils.tspackages/2-sql/1-core/contract/src/canonicalization-hooks.tspackages/2-sql/1-core/contract/src/ir/sql-storage.tspackages/2-sql/1-core/contract/src/ir/storage-type-instance.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/sql-storage.test.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/contract.parameterized-types.test.tspackages/2-sql/2-authoring/contract-ts/test/cross-space-relation.test.tspackages/2-sql/4-lanes/relational-core/src/codec-ref-for-column.tspackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/5-runtime/test/codec-integrity.test.tspackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/end-contract.d.tspackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/end-contract.jsonpackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/migration.jsonpackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/migration.tspackages/3-extensions/pgvector/migrations/refs/head.jsonpackages/3-extensions/pgvector/src/contract.d.tspackages/3-extensions/pgvector/src/contract.jsonpackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/end-contract.d.tspackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/end-contract.jsonpackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/migration.jsonpackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/migration.tspackages/3-extensions/postgis/migrations/refs/head.jsonpackages/3-extensions/postgis/src/contract.d.tspackages/3-extensions/postgis/src/contract.jsonpackages/3-extensions/supabase/src/contract/contract.d.tspackages/3-extensions/supabase/src/contract/contract.jsonpackages/3-extensions/supabase/test/contract-handles.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.tstest/integration/test/authoring/parity/core-surface/expected.contract.json
💤 Files with no reviewable changes (3)
- packages/1-framework/3-tooling/emitter/test/utils.ts
- packages/2-sql/1-core/contract/src/canonicalization-hooks.ts
- examples/supabase/src/handlers.ts
f86adb6 to
5ca6d89
Compare
5ca6d89 to
a063265
Compare
… record cast in cross-space-relation test Add `readonly spaceId?: string` to the FK target object literal inside BuiltStorageTables<Definition>, so cross-space relation FKs surface the already-emitted runtime spaceId through the typed contract surface. The field is optional — local FKs continue to type-check unchanged. Drop the `as unknown as Record<string, unknown>` cast at cross-space-relation.test.ts:300; the test now reads `fks[0]!.target.spaceId` directly against the typed surface. Signed-off-by: Will Madden <[email protected]>
…1 follow-up) Mirrors the R1 drop at cross-space-relation.test.ts:300. The BuiltStorageTables FK target now exposes the optional spaceId field (added in cf2cd49), so the `as Record<string, unknown>` cast and its stale "narrow type which omits spaceId" justification are obsolete. The test now reads `fk.target.spaceId` against the typed surface. Signed-off-by: Will Madden <[email protected]>
…the runtime boundary
PSL emits `typeParams: {}` for `@db.X` named types whose body carries
no parameters (e.g. `types { Uuid = String @db.Uuid }` in the supabase
extension). The runtime validator previously rejected any column whose
codec ref carried `typeParams !== undefined` against a non-parameterized
codec descriptor, so any contract using such an alias died at
`createExecutionContext` with `CODEC_PARAMETERIZATION_MISMATCH`.
Reconcile the two views around the design principle: at every runtime
comparison boundary, `typeParams: {}` and missing `typeParams` mean the
same thing — "no parameters were supplied". The on-disk JSON shape and
the IR types are unchanged; only the JS-side comparison behavior is
canonicalized.
Three runtime surfaces canonicalize empty typeParams:
- `codecRefForStorageColumn` (codec-ref-for-column.ts): a typeRef-shaped
column whose alias carries empty typeParams now produces a `CodecRef`
with no `typeParams` field. Same for inline-typeParams columns whose
`typeParams` value happens to be `{}`. This keeps content-keyed
memoisation honest (`{codecId}` and `{codecId, typeParams: {}}` resolve
to the same cache key) and stops a stray `{}` from tripping the
validator downstream.
- `assertColumnCodecIntegrity` (sql-context.ts): non-parameterized
codecs only conflict with typeParams that carry at least one key. An
empty object is treated as equivalent to absent.
- `buildContractCodecRegistry` typeRef walk (sql-context.ts): codec-ref
construction for `storage.types[name]` entries matches the
codec-ref-for-column canonicalization, so the pre-population walk uses
the same cache key as the column walk.
New focused unit tests cover both forms (inline column + typeRef-shaped
column) against a non-parameterized codec descriptor. Both tests fail
against the pre-change code and pass after.
Signed-off-by: Will Madden <[email protected]>
…validator) R1 (7c76339) shipped runtime-side equivalence between empty and missing `typeParams` at every comparison boundary. R2 finishes the job at the on-disk boundary by dropping the SQL-side preserve-empty entry for `storage.types.*.typeParams` and re-emitting the affected extension contracts + migration baselines. Three coordinated changes: - `packages/2-sql/1-core/contract/src/canonicalization-hooks.ts`: remove the `[storage, types, *, typeParams]` preserve-empty path so `omitDefaults` strips `typeParams: {}` the same way it strips every other empty default. The Mongo-family hook file already had no equivalent entry. - `packages/2-sql/1-core/contract/src/validators.ts` + `ir/storage-type-instance.ts`: make `typeParams` optional on the codec-instance schema and IR shape. The on-disk canonical form now omits `typeParams: {}`, so the validator must accept the absent form; the runtime already treats absent and `{}` as equivalent (R1). Mechanical regeneration (via `pnpm fixtures:emit`): - supabase/pgvector/postgis `src/contract.{json,d.ts}` re-emitted without the empty `typeParams` field, producing new storageHashes. - pgvector/postgis migration baselines re-pinned via `pnpm migrations:regen` (head.json + migration.{ts,json} + ops.json + end-contract.{json,d.ts}). supabase has no on-disk migrations tree. - `test/integration/test/authoring/parity/core-surface/expected.contract.json` regenerated through the parity fixtures pipeline. Tests: - New focused case in emitter `canonicalization.test.ts` asserting `{codecId, nativeType, typeParams: {}}` canonicalizes to `{codecId, nativeType}` under SQL hooks. - Updated `canonicalization.test.ts` in the foundation package: empty `typeParams` is now stripped even with the SQL hook; new case covers non-empty `typeParams` preservation. - Updated `canonicalization-path-match.test.ts` to assert the inverted predicate behavior. - Renamed the previously-passing "rejects type instance missing typeParams" case in `contract.parameterized-types.test.ts` to "accepts type instance with omitted typeParams" — missing is now the canonical form for empty. Validation: typecheck 138/138 clean; lint + lint:deps clean; all affected packages green (sql-contract 157/157, sql-contract-ts 326/326, sql-runtime 269/269, contract 169/169, emitter 166/166, sql-contract-psl 227/227, supabase 19/19, pgvector 140/140, postgis 87/87). Signed-off-by: Will Madden <[email protected]>
…eParams optional flip
R2 flipped `StorageTypeInstance.typeParams` from required to optional on
the IR but missed downstream construction sites. Under
`exactOptionalPropertyTypes: true` an explicit `typeParams: x` where `x`
is `T | undefined` is not assignable to a target with `typeParams?: T`.
Fixes:
- planner-strategies.ts: read site uses optional chaining (`?.[`).
- 4 construction sites (postgres planner-type-resolution,
postgres planner-ddl-builders, sqlite planner-ddl-builders,
family-sql contract-to-schema-ir, family-sql verify-sql-schema):
use `...ifDefined('typeParams', x)` to omit the property when
the source is undefined.
The sqlite `planner-ddl-builders.ts:146` site is the same mechanical
pattern as the postgres/family-sql ones; it surfaced when the
family-sql cascade unblocked downstream package typechecks.
Full repo `pnpm typecheck`: 138/138 PASS.
Signed-off-by: Will Madden <[email protected]>
… handler + M1 test for the new NOT NULL userId Signed-off-by: Will Madden <[email protected]>
…ses AC4 + AC7) Signed-off-by: Will Madden <[email protected]>
Project workspace artifacts for slice M3b — cross-contract FK walking skeleton + cascade-delete test + BuiltStorageTables.spaceId type-surface cleanup + the typeParams empty-state equivalence substrate fix that surfaced during execution. projects/cross-contract-refs/slices/M3b/spec.md — slice spec projects/cross-contract-refs/slices/M3b/plan.md — dispatch plan projects/cross-contract-refs/trace.jsonl — emit-as-you-go trace reviews/code-review.md and learnings.md are intentionally gitignored (transient working state per projects/.gitignore). Signed-off-by: Will Madden <[email protected]>
… cascade test ORM)
F3: Make StorageTypeInstance.typeParams required in the in-memory IR. Revert
six ifDefined wrapper sites added in M3b.2 where the source is a
StorageTypeInstance. The SqlStorage constructor normalises on-disk objects
that omit typeParams (canonical compact form) to typeParams: {} via
normaliseTypeEntry, using a runtime 'in' check so it only allocates a new
object when the property is genuinely absent. StorageTypeInstanceInput keeps
typeParams optional; the arktype validator also keeps it optional for on-disk
compatibility. Added a test for the normalisation behaviour.
F4: Remove the userId seed and insertAndReadProfile round-trip from the M1 it
block — those steps don't prove the FK exists. Delete handlers.ts (dead code).
The M1 it retains only its original three claims: zero DDL for auth/storage,
db verify passes, raw auth.users read.
F5: Refactor the cascade it so that public.profile operations go through the
ORM runtime (db.connect + runtime.execute) and auth.users operations remain
raw SQL via withClient. Both clients are open simultaneously; the try/finally
block calls db.close() to clean up the ORM runtime.
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
`SqlNamespace.entries.table` is already typed as `Readonly<Record<string, StorageTable>>`, which is exactly what the local `SqlNamespaceTables` alias expanded to. The five cast sites and the alias itself were all no-ops; removing them drops the bare-cast ratchet count by 4 (from 1274 to 1269 vs merge-base). This unblocks the Lint CI check. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…+ extension regen
- examples/supabase: add cross-space-fk-psl-pattern entry documenting
the types { Uuid } + supabase:auth.AuthUser @relation PSL authoring
pattern (new opt-in feature; no action for existing consumers).
- packages/3-extensions/: add regen-extension-contracts-strip-empty-type-params
entry covering the typeParams: {} canonicalization — extension authors
with named-type aliases must re-emit + re-pin migration baselines.
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
a063265 to
355f1ff
Compare
…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]>
After this PR, an app contract can declare a foreign key from a local model to a model owned by an extension's contract — and the framework turns it into a real Postgres FK constraint with the standard referential actions. The grounding example, from
examples/supabase/src/contract.prisma:The new bit is
Profile.user.supabase:auth.AuthUserreads broad-to-narrow: modelAuthUserin namespaceauthof contract spacesupabase. Thesupabasespace comes from@prisma-next/extension-supabase; the app declares its dependency viaextensionPacksinprisma-next.config.ts. The colon-prefix is the only new PSL grammar — the@relationattribute is unchanged from local FKs.The DDL the planner emits at migration time:
That's the deliverable: cross-contract foreign keys are first-class, complete with cascade-delete semantics realized through the live database constraint.
How the PR is structured
The substrate that makes this possible — the IR carrier with
spaceId, the PSL grammar, the brand handles, the planner, the verifier, the aggregate resolution — already shipped in earlier slices of this project. This PR is the first consumer that drives it through the example app's normalprisma-next contract emitflow and proves it works against a live database.Three things land:
1. The walking-skeleton wire-up.
examples/supabase/src/contract.prismadeclares the cross-contract FK shown above. The standard CLI emit flow (pnpm --filter @prisma-next/example-supabase emit) regenerates the example'scontract.json+contract.d.tscleanly.2. A hermetic cascade-delete integration test. A new
itblock inexamples/supabase/test/skeleton.integration.test.tsseeds anauth.usersrow via raw SQL (cross-space — no ORM access by design, see Decision below), inserts apublic.profilerow through the ORM that references the seeded user, asserts the row is present, deletes theauth.usersrow, and assertspublic.profileis empty. This proves both that the FK constraint really exists inpg_constraintand thatON DELETE CASCADEactually fires through it.3. Two cleanups the walking-skeleton surfaced.
Typed
spaceIdon the contract surface. The TS contract surface (BuiltStorageTables<Definition>) didn't exposespaceIdon cross-space FK targets, even though the runtime carrier already had it. Before this PR, consumers had to cast throughas Record<string, unknown>to read the field. After, it's a typed read.typeParamsempty-state canonicalization. The walking-skeleton was the first runtime consumer to drive a Supabase-extension-style named type (Uuid = String @db.Uuid) through the app's runtime client — and tripped on a representation inconsistency. The PSL emitter wrotetypeParams: {}for empty named types; the runtime validator rejectedtypeParams: {}against non-parameterized codecs; the IR mixed required and optional shapes. The fix makes emptytypeParamscanonical at every boundary: the on-disk JSON omits it (canonicalizer strips); the in-memory IR always carriestypeParams: {}(construction normalizes); codecs receive a consistent empty form. Extension contracts (supabase, pgvector, postgis) are re-emitted viapnpm fixtures:emit, which automatically re-pins their migration baselines.Decision: cross-space relations are declared but non-navigable
The cross-space relation is a real relationship in the contract — it drives the FK constraint and appears in introspection — but ORM traversal across spaces is a compile-time error. Writing
db.public.Profile.find({ include: { user: true } })does not type-check.The reason: this is the canonical Supabase usage pattern. Apps reference
auth.usersfor the cascade-delete guarantee; they don't queryauth.usersdirectly from the app. Cross-space querying would need a runtime contract-space aggregate that merges loaded spaces into the queryable surface, which doesn't exist today. The injection seam (when we eventually design it) isExecutionContext, not a mergedDb<C>type.This is why the cascade test uses raw SQL for
auth.usersoperations (no ORM surface to use) but the ORM forpublic.profileoperations (the app's own model, where the ORM is the right tool).Validation
pnpm typecheck: 138/138pnpm lint: 79/79pnpm lint:deps: cleanpnpm fixtures:check: cleanpnpm test:packages: 9934 passed (4 expected-fail, 3 skipped)pnpm --filter @prisma-next/example-supabase test: 2/2 (M1 walking-skeleton + new cascade test)Test plan
pnpm --filter @prisma-next/example-supabase test.itstill proves what it originally claimed (zero DDL forauth.*/storage.*;db verifypasses;auth.usersreachable via raw client) — the M1itis deliberately FK-agnostic so the cascadeitis the sole FK assertion.Alternatives considered
Field-level
@db.Uuidinstead of atypes {}block. Early dispatch attempts wroteuserId String @db.Uuid @uniquedirectly on the field. The PSL grammar only accepts@db.Xinsidetypes { Name = T @db.X }declarations — field-level use is rejected. The named-type pattern is the canonical idiom and is the same shape the supabase extension itself uses internally.Auto-propagating the target's native type via the brand. First instinct was that M2's
ColumnRef<TSpaceId>brand would auto-match the source column to the target's storage type. The brand carriesspaceIdfor resolution, not storage type. PSL authors are responsible for native-type matching on cross-space FK source columns — same rule as for local FKs whose target isn't the PSL default type.Three options for the
typeParamsempty-state fix. We considered:{}and missing as equivalent at the JS comparison boundary, leave the on-disk redundancy alone. Smallest blast radius. Rejected: leaves the on-disk inconsistency (extension contracts shiptypeParams: {}indefinitely) and only papers over the misalignment.typeParams: {}via the canonicalizer; normalize the in-memory form to{}. What landed. The canonicalizer already had this exact pattern for other empty-defaults; the deferred work was small. Migration baselines re-pin automatically via the existingpnpm migrations:regenscript.pg/uuidcodec descriptor. The architecturally cleanest answer — stops@db.Uuidfrom masquerading aspg/text@1withnativeType: 'uuid'. Rejected for this PR: it's a project's worth of work touching every consumer of@db.Uuid. Reasonable follow-up.Required
typeParams: Record<string, unknown>vs optionaltypeParams?. An early version of the substrate fix flippedStorageTypeInstance.typeParamsto optional, mirroring the on-disk form directly. Reverted: the in-memory contract is "empty ={}", not "empty = undefined". Codecs read a canonical empty form consistently. The validator schema stays permissive on input (the on-disk form genuinely omits); construction normalizes.Splitting M3b into two PRs. The substrate fix could have shipped as its own PR with the walking-skeleton waiting. We chose to bundle: the substrate fix has its narrative anchor — the walking-skeleton is what tripped on it. A standalone substrate-fix PR would have read as "fix a thing nobody noticed was broken." This PR is wider than originally planned but coherent: one decision (cross-contract FKs as first-class), one walking-skeleton proof, plus the substrate cleanup the proof required.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests
Chores