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

ADR 231: Declarative attribute specifications - #889

Merged
SevInf merged 1 commit into
mainfrom
psl-attributes
Jun 29, 2026
Merged

SevInf merged 1 commit into
mainfrom
psl-attributes

Conversation

@SevInf

@SevInf SevInf commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

n/a — no Linear issue. This PR adds a single design document (ADR 231) capturing a decision reached in discussion; it ships no code.

At a glance

The ADR proposes describing each PSL attribute once, as data. A relation:

model Post {
  authorId Int
  author   User @relation(fields: [authorId], references: [id], onDelete: Cascade)
}

is described by one declarative spec:

const sqlRelation = fieldAttribute('relation', {
  positional: [{ key: 'name', type: optional(str()) }],
  named: {
    name:       optional(str()),
    fields:     optional(list(fieldRef('self'),       { nonEmpty: true })),
    references: optional(list(fieldRef('referenced'), { nonEmpty: true })),
    map:        optional(str()),
    onDelete:   optional(enumOf('NoAction', 'Restrict', 'Cascade', 'SetNull', 'SetDefault')),
    onUpdate:   optional(enumOf('NoAction', 'Restrict', 'Cascade', 'SetNull', 'SetDefault')),
  },
  refine: relationInvariants,
});

interpretAttribute(node, spec, ctx) turns a parsed AST node into a strongly-typed object whose shape is inferred from the spec — and the same spec is read by the language server for completion, go-to-definition, and find-usages.

Decision

Add docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md (Status: Proposed). The ADR records a decision to replace per-attribute hand-written validation with a declarative AttributeSpec per field/model/block attribute, composed from a fixed framework combinator kit:

  • generic list / map / record over native PSL literals;
  • enumOf for fixed literal sets (string, numeric, or mixed);
  • oneOf as an ordered, diagnostic-pure sum over alternative combinators;
  • recursive funcCall / funcCallFrom that reuse the same positional/named argument model;
  • fieldRef(scope) / modelRef() / codecRef() reference combinators, where scope records whether a field name resolves against our model or the referenced model.

The motivating reason is reuse across consumers: attribute arguments are opaque to the language server today because their shape lives only as imperative interpreter code. One declarative description serves both the family interpreters and the editor.

How it fits together

The ADR follows the house format — At a glance, Decision, numbered Design principles, build-up sections (the combinator kit, positional/named model, type inference, resolution context, a dedicated language-server features section, cross-argument refinement, surface policy), an explicit Out of scope for @db.* native types, then Consequences, Alternatives considered, Open questions, and References.

It was calibrated against two siblings: ADR 225 (three-layer extensibility for pack-contributed kinds — the contribution model the spec registry follows) and ADR 224 (control policy — the framework-vocabulary / family-dispatch split, and the @@control value set the spec types with enumOf).

Reviewer notes

  • Proposed, not Accepted. The ADR carries five open questions (runtime-only field-type matching for @default, index-element strictness, alias ergonomics, whether to fold generic-block parameters in, where collection-level invariants live). Status is deliberately Proposed pending ratification.
  • Scope boundary on @db.*. The ADR explicitly excludes @db.* native types, because they attach to named-type declarations (type Slug = String @db.VarChar(191)), not to fields or models. This is stated as an out-of-scope section, not an omission.
  • Surface policy. The ADR commits to native PSL literals for structured arguments, with quoted-JSON kept only for an arbitrary document (filter). This reflects a decision to drop the quoted-string form for include/exclude/weights, whose only current usage is in tests.
  • Code samples are illustrative. No combinator kit exists yet; the snippets describe the proposed surface, and the example PSL was checked against real schemas (examples/supabase, examples/mongo-blog-leaderboard).

Testing performed

n/a — documentation only. Verified the four referenced ADRs (126, 221, 224, 225) and two pattern docs (frozen-class-ast, three-layer-polymorphic-ir) resolve to existing files. There is no doc test suite to run.

Skill update

n/a — adds an architecture decision record; no user-facing surface (CLI, public TypeScript API, config, error codes) changes.

Checklist

  • All commits are signed off (git commit -s) per the DCO.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated (n/a — doc-only, no behavioural delta).
  • The PR title is in TML-NNNN: <sentence-case title> form — intentionally omitted; this ADR has no Linear issue.
  • The Skill update section above is filled in.

Alternatives considered

The ADR's own Alternatives considered section weighs: keeping hand-written per-attribute validation; dispatching oneOf with a recognition predicate instead of ordered try-each; separate enumOf/numEnum; a codec-validated json(codecId); quoted-string surfaces for lists and maps; and monomorphic collection leaves. Each is recorded there with the reason it was not taken.

Summary by CodeRabbit

  • Documentation
    • Added a new architecture decision record describing a shared, declarative approach for attribute argument specifications.
    • Clarified how argument parsing and validation align with editor tooling, including completions and navigation for structured arguments.
    • Documented supported argument patterns such as optional/default values, collections, choice-based arguments, and function-call style forms.
    • Recorded policy decisions, exceptions, and open questions for future follow-up.

@SevInf
SevInf requested a review from a team as a code owner June 29, 2026 14:15
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: bf18b6fc-5c29-48a3-952a-618d67b64312

📥 Commits

Reviewing files that changed from the base of the PR and between f41116a and 44f04d0.

📒 Files selected for processing (1)
  • docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md
✅ Files skipped from review due to trivial changes (1)
  • docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md

📝 Walkthrough

Walkthrough

Adds ADR 231 proposing a declarative, composable attribute-specification model for PSL, with shared typing, parsing, and language-server behavior for attribute arguments.

Changes

ADR 231: Declarative Attribute Specifications

Layer / File(s) Summary
Motivation, decision, and design principles
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md
Describes the validation mismatch, defines the shared AttributeSpec decision, and sets the attribute-spec scope boundaries.
Combinator kit, spec structure, and type inference
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md
Defines ArgType<T>, positional/named argument mapping, aliasing, and InferAttr<S> output inference.
oneOf, funcCall, InterpretCtx, and language-server integration
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md
Specifies recursive parsing combinators, resolution context, completion/navigation behavior, refinement, and surface policy.
Consequences, alternatives, open questions, and references
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md
Summarizes consequences, rejected alternatives, open questions, and related references.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

Poem

🐇 Hoppity-hop, the specs align,
Arguments now dance by shared design.
oneOf leaps, funcCall glows,
The language server follows where the rabbit goes.
One ADR, one tidy trail—✨
A declarative burrow, strong and well!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the new ADR about declarative attribute specifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch psl-attributes

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.

❤️ Share

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

@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.

🧹 Nitpick comments (1)
docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md (1)

255-255: 📐 Maintainability & Code Quality | 🔵 Trivial

Clarify static vs. runtime type for matchingScalarLiteral().

The open question notes the "static output stays the general default-value union" because the field type isn't known where the spec is defined. Consider whether this is a fundamental limitation or could be addressed by making specs parametric on field type (e.g., fieldAttribute<T>(...)), or if the runtime check is an acceptable tradeoff. Worth a brief note in the ADR if this tension is intentional.

🤖 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 `@docs/architecture` docs/adrs/ADR 231 - Declarative attribute
specifications.md at line 255, Clarify the type-modeling choice around
matchingScalarLiteral() by explicitly noting whether the general default-value
union is a fundamental limitation or an intentional tradeoff. Update the ADR
section that discusses matchingScalarLiteral() and the fieldAttribute/spec
definition to mention the possibility of parametric typing (for example, a
generic fieldAttribute<T>(...)) versus keeping the runtime check via ctx.field,
and state which approach is intended.
🤖 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.

Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 231 - Declarative attribute
specifications.md:
- Line 255: Clarify the type-modeling choice around matchingScalarLiteral() by
explicitly noting whether the general default-value union is a fundamental
limitation or an intentional tradeoff. Update the ADR section that discusses
matchingScalarLiteral() and the fieldAttribute/spec definition to mention the
possibility of parametric typing (for example, a generic fieldAttribute<T>(...))
versus keeping the runtime check via ctx.field, and state which approach is
intended.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 6cc23473-b1cb-4a0e-addc-bf83c4bbc92c

📥 Commits

Reviewing files that changed from the base of the PR and between 291f931 and f1721e5.

📒 Files selected for processing (1)
  • docs/architecture docs/adrs/ADR 231 - Declarative attribute specifications.md

@wmadden wmadden 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.

Looks good! A couple of small notes below


**Scalars** read a single token. `str()` parses a quoted string. `int({ min, max })` parses a number. `bool()` parses a boolean. `enumOf(...values)` parses a member of a fixed literal set — and because a member may be a string or a number, the set may be homogeneous *or* mixed. Mongo's index `type`, which accepts the numbers `1`/`-1` and the strings `"text"`/`"2dsphere"`/`"2d"`/`"hashed"`, is a single `enumOf(1, -1, 'text', '2dsphere', '2d', 'hashed')`. `json()` reads an opaque JSON value from a quoted string; it is the one place a structured value is text-encoded (see [Surface policy](#surface-policy-native-literals-with-one-text-exception)).

**References** resolve a name against something in the surrounding contract, so they depend on the [resolution context](#resolution-context). `fieldRef(scope)` resolves a field name, where `scope` is `'self'` (a field of the model declaring the attribute), `'referenced'` (a field of a relation's target model), or `'document'` (a free path, for wildcard projections). `modelRef()` resolves a model name. `codecRef()` resolves a registered codec id.

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.

This should be generalized to a reference to any entity, since the contract can already contain arbitrary pack-contributed entity types, not just to model/field.

Propose a declarative spec for field/model/block PSL attributes,
composed from a fixed combinator kit and interpreted into a
strongly-typed object whose shape is inferred from the spec. The same
spec is reused by the family interpreters and the language server
(completion, go-to-definition, find-usages), replacing the per-attribute
hand-written validation that is opaque to the editor today.

Status: Proposed.
Signed-off-by: Serhii Tatarintsev <[email protected]>
@SevInf
SevInf merged commit eba2814 into main Jun 29, 2026
19 checks passed
@SevInf
SevInf deleted the psl-attributes branch June 29, 2026 16:23
SevInf added a commit that referenced this pull request Jul 7, 2026
## What this is

Slice 1 of 3 implementing [ADR 231 — Declarative attribute
specifications](https://github.com/prisma/prisma-next/blob/main/docs/architecture%20docs/adrs/ADR%20231%20-%20Declarative%20attribute%20specifications.md),
scoped to the **family interpreters**. It stands up the
declarative-attribute engine in `psl-parser` and proves it end-to-end by
migrating the SQL `@relation` attribute off its hand-written parser.

Language-server integration (completion, go-to-definition over attribute
arguments) is the follow-up this unblocks — and the reason the work
lands under the *Language Tools Support Prisma Next PSL* project — but
is **not** in scope here.

## Why

Each family interpreter validated attribute arguments with hand-written
code that pulled raw text out of the AST and re-checked its shape —
`split(',')` on field lists, ad-hoc quoted-string unwrapping,
per-attribute unknown-argument rejection — duplicated across the SQL and
Mongo interpreters. The output type drifted freely from the validation,
and no other consumer (the language server) could read what an attribute
accepts. ADR 231 replaces that with one declarative `AttributeSpec` per
attribute, read by `interpretAttribute`, with the output type **inferred
from the spec**.

## What's in this slice

- **The engine + core types in `psl-parser`** — `ArgType`,
`AttributeSpec`, `optional`/`fieldAttribute`, `interpretAttribute`,
`InferAttr`, `InterpretCtx` — consuming the parser's `ExpressionAst` CST
directly.
- **The combinators `@relation` needs** — `str`, `enumOf`,
`fieldRef(scope)`, `list({ nonEmpty, unique })`, plus a small
`identifierName` leaf for bare-identifier enum values.
- **SQL `@relation` migrated** to a declarative `sqlRelation` spec
lowered through `interpretAttribute`; the hand-written
`parseRelationAttribute` is deleted.

## Key decisions

- **Combinators consume `ExpressionAst` directly** — no new intermediate
argument representation. The CST already carries native literals and
real spans.
- **The kit lives in `psl-parser`**, which already owns `ExpressionAst`
and the `SymbolTable`. No new package.
- **Diagnostic-code parity via `InterpretCtx.diagnosticCode`** — the
engine threads the spec's code (here `PSL_INVALID_RELATION_ATTRIBUTE`)
to every leaf, so codes stay byte-identical.
- **`onDelete`/`onUpdate` keep `normalizeReferentialAction` as
validator** — they parse to the raw identifier name (no parse-time set
check), preserving the existing `PSL_UNSUPPORTED_REFERENTIAL_ACTION`
code + span. `enumOf` is intentionally not used for them.
- **Parity bar (this project):** contract output and diagnostic
**codes** are byte-identical; **spans** are no-coarser (the kit's
per-argument anchoring narrows three `@relation` leaf spans — strictly
more precise, exercised by no fixture); **messages** may adopt the kit's
phrasing; malformed inputs legacy tolerated by coincidence (a quoted
`onDelete: "Cascade"`) are now rejected. The span + message +
stricter-rejection relaxations were explicitly ratified.

## Deliberately out of scope

Other SQL attributes (`@id`, `@unique`, `@@index`, `@default`, `@map`,
`@@control`, `@@discriminator`, `@@base`) → slice 2. All Mongo
attributes → slice 3. The rest of ADR 231's combinator alphabet (`int`,
`bool`, `json`, `map`, `record`, `entityRef`, `codecRef`, `oneOf`,
`funcCall`, `modelAttribute`, `blockAttribute`) is added as later slices
need it. `@db.*` native types and the TypeScript builder surface are out
of the whole project.

## Validation

- `psl-parser`: 504 tests pass (engine + combinators + type-level
inference); typecheck + lint clean.
- `@prisma-next/sql-contract-psl`: 271 tests pass — the `@relation`
relations + diagnostics suites pass with **zero test edits**.
- `pnpm fixtures:check` clean (no contract/migration drift);
cross-package `pnpm typecheck` 143/143.

Refs: TML-2956 · ADR 231 (#889).


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

* **New Features**
* Added new PSL attribute-spec combinators (string, identifier, lists
with `nonEmpty`/`unique`, optional values, and `oneOf` alternatives),
plus field-level helpers and public exports to support
authoring/interpretation.
* Relation attribute parsing now uses these declarative attribute specs
for consistent handling.
* **Bug Fixes**
* Improved span-aware, code-specific diagnostics for invalid, missing,
and duplicate relation/attribute arguments.
* Simplified referential action handling with clearer, unified error
reporting.
* **Tests**
* Added/updated type-level and runtime test coverage for attribute
combinators and relation interpretation.
* **Documentation**
  * Updated the ADR to reflect `oneOf(identifier(...))` usage.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Serhii Tatarintsev <[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