Skip to content

TML-2956: migrate Mongo family attributes to declarative specs - #29833

Open
StevenMcClankerton wants to merge 16 commits into
mainfrom
tml-2956-mongo-attributes
Open

TML-2956: migrate Mongo family attributes to declarative specs#29833
StevenMcClankerton wants to merge 16 commits into
mainfrom
tml-2956-mongo-attributes

Conversation

@StevenMcClankerton

@StevenMcClankerton StevenMcClankerton commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2956 — "Language Tools Support Prisma Next PSL" (the typed-attribute-parsers project's umbrella ticket).

Completes the family migrations begun in #932 (SQL non-@default attributes) and #938 (SQL @default): this PR brings the Mongo family onto the same declarative attribute-spec kit. After it, every attribute in both families validates its arguments through the kit — no hand-written string parsers remain.

At a glance

Every Mongo attribute is now described by an AttributeSpec and lowered through interpretAttribute. The interesting one is the @@index field element — email, email(sort: Desc), and wildcard(tags) are all composed from existing combinators, built per model from its field names (the same dynamic-composition pattern @default uses over its function registry):

const sortSig = { named: { sort: oneOf(identifier('Asc'), identifier('Desc')) } } satisfies FuncCallSig;

function indexFieldElement(fieldNames: readonly string[]): ArgType<string | TypedFuncCall> {
  return oneOf(
    fieldRef('self'),                                                                            // email          → "email"
    funcCall('wildcard', { positional: [{ key: 'scope', type: optional(fieldRef('self')) }] }),  // wildcard(tags)  → { fn: 'wildcard', … }
    ...fieldNames.map((name) => funcCall(name, sortSig)),                                          // email(sort: Desc) → { fn: 'email', args: { sort } }
  );
}

Previously the Mongo interpreter parsed every attribute imperatively off a resolved ResolvedAttribute view via psl-helpers.ts string scanners (parseIndexFieldList, parseRelationAttribute, parseCollation, getNamedArgument, …). All of that is gone.

Decision

This PR makes the Mongo family fully spec-driven, mirroring the SQL family:

  1. Mongo InterpretCtx wiring — a new mongo-attribute-specs.ts provides the family-agnostic interpretModelAttribute/interpretFieldAttribute wrappers + ctx builders (a copy of the SQL shape, not a cross-family import).
  2. Every Mongo attribute migrated@map/@@map, @relation, @@discriminator/@@base, @@index/@@unique, and @@textIndex now parse their arguments through specs.
  3. Two new kit combinatorsstr(value) (pinned string literal, for the index type set) and json() (the ADR's one text-encoded exception, for filter/weights).
  4. No bespoke index-element combinators — the sketched sortedFieldRef/wildcardPath dissolve into funcCall composition over the model's fields (ADR 231 principle 4, "compose don't special-case").
  5. Legacy parsers deleted — every Mongo attribute-argument string parser is removed behind a grep gate; the interpreter keeps only the genuinely-semantic logic.

How it fits together

  1. Wiring first (@map/@@map). mongo-attribute-specs.ts lands the ctx wiring, proven by migrating the simplest attribute — the mapped field/collection name — end-to-end.
  2. The simple attributes. @relation (name alias + fields/references via fieldRef), then @@discriminator/@@base (field / model-name + value), each replacing a string scanner while leaving the cross-model semantics (backrelation matching, polymorphism consistency) untouched.
  3. The kit leaves. str(value) and json() are added to psl-parser — the only new combinators the whole slice needs.
  4. The index grammar. @@index/@@unique then @@textIndex migrate to per-model specs (the dynamic field element + the full named-arg surface — type, sparse, expireAfterSeconds, filter, include/exclude, weights, language, and the 9 collation args). The dense index-shape validation stays in the interpreter, reading normalized values.
  5. Cleanup. With all three index attributes spec-driven, the orphaned parsers are deleted; a grep gate proves none remain.

Behavior changes & evidence

  • Every Mongo attribute is spec-validated. See mongo-attribute-specs.ts (the specs + wiring) and interpreter.ts (the migrated call sites); byte-identical contract output proven by interpreter.test.ts + fixtures:check.
  • Field-existence errors split coherently (operator "Option A"). A field that doesn't exist on the model → PSL_INVALID_ATTRIBUTE_SYNTAX (rejected at parse by fieldRef, consistent with SQL @relation); a field that exists but isn't indexable (a relation field) → the semantic PSL_INDEX_FIELD_NOT_FOUND (downstream). Evidence in interpreter.test.ts + interpreter.polymorphism.test.ts.
  • Two new kit combinators. str(value) pins a string literal; json() reads an opaque JSON object from a quoted string. See str.ts + json.ts; evidence in attribute-spec-combinators.test.ts.
  • Legacy parsers gone. psl-helpers.ts shrinks from a bag of string scanners to a handful of survivors (getAttribute, lowerFirst, parseProjectionList, parseQuotedStringLiteral).

Reviewer notes

  • No bespoke index-element combinators. sortedFieldRef/wildcardPath were considered and dropped: field(sort: Desc) is funcCall(field, { named: { sort } }) and wildcard(scope) is funcCall('wildcard', …), so the element is oneOf over fieldRef + the per-field funcCall arms — pure composition, built dynamically per model.
  • Diagnostic-code shifts are intentional (Option A, consistent with Hanging on "Preparing your database ..." during tutorial #932/prisma2 needs a more security conscious installation method for binaries #938). Malformed/unknown index arguments (an unknown type, a non-bool sparse, invalid filter/weights JSON, a bad sort) become PSL_INVALID_ATTRIBUTE_SYNTAX; @@textIndex now rejects args it doesn't accept (type/sparse/expireAfterSeconds) where the old path silently ignored them. All PSL_INVALID_INDEX shape rules, the one-@@textIndex-per-collection guard, and PSL_INDEX_FIELD_NOT_FOUND (for relation fields) are preserved.
  • Coarse-diagnostic trade-off (accepted, ADR 231). Because the index element is oneOf, an absent-field reference surfaces as a generic Expected one of: … rather than naming the field — the same trade-off the SQL slices accepted. A future oneOf-diagnostic enhancement could restore field-naming; out of scope here.
  • Multiple @@index on one model. findModelAttributeNode returns the first same-named node, so the loop maps each resolved attribute to its AST node by position (node.attributes() order is 1:1 with the resolved list) — guarded by a new multi-index test.
  • Largest diff: interpreter.ts (collectIndexes) — the index-shape validation and MongoIndex construction are byte-for-byte unchanged; only the argument source moved from string parsers to the spec output.
  • Project artefacts under projects/typed-attribute-parsers/slices/mongo-attributes/ are included for review provenance (path-filtered out of automated review); they are migrated/removed at project close-out.

Verification

Run on final HEAD:

  • pnpm --filter @prisma-next/mongo-contract-psl build && typecheck && test — clean; 155 tests
  • pnpm --filter @prisma-next/psl-parser build && typecheck && test — clean; 635 tests
  • pnpm --filter @prisma-next/sql-contract-psl test346 (unaffected by the additive kit changes)
  • pnpm build — 68/68 · pnpm fixtures:check — clean, no contract drift · pnpm lint:deps — 0 · pnpm lint:framework-vocabulary — 836/836
  • Grep gate: the legacy Mongo attribute parsers (parseIndexFieldList/parseRelationAttribute/parseCollation/getNamedArgument/…) — zero remaining in contract-psl/src

Alternatives considered

  • Bespoke sortedFieldRef/wildcardPath combinators. Rejected: with the model in context the field names are known, so oneOf(fieldRef, ...fields.map(funcCall), funcCall('wildcard')) composes the same grammar without new kit surface — the same reason @default dropped funcCallFrom.
  • Changing the text-encoded index surface (filter/weights quoted JSON → object literals; include/exclude quoted bracket-strings → native lists). Rejected: it would break existing Mongo schemas. json() preserves the quoted-JSON surface; include/exclude stay str() + parseProjectionList.
  • Preserving PSL_INDEX_FIELD_NOT_FOUND for all field misses. Rejected: fieldRef validates existence at parse time, and the natural split (missing → syntax, relation-field-not-indexable → semantic) is both cleaner and consistent with how @relation already behaves.

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 (the Mongo family attribute migration).
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form.

Summary by CodeRabbit

  • New Features

    • Added JSON object parsing for attribute arguments.
    • Added support for matching string attributes against a specific expected value.
    • Improved MongoDB PSL attribute handling for mappings, relations, polymorphism, and indexes.
  • Bug Fixes

    • Improved validation and source locations for invalid attributes and index definitions.
    • Correctly preserves multiple index declarations on the same model.

@StevenMcClankerton
StevenMcClankerton requested a review from a team as a code owner July 28, 2026 16:21
@CLAassistant

CLAassistant commented Jul 28, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Jul 28, 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 Plus

Run ID: 7b7ac997-0a0c-4491-8a5b-2efef7229fe9

📥 Commits

Reviewing files that changed from the base of the PR and between 5c0e4bd and e491496.

⛔ Files ignored due to path filters (8)
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/01-mongo-wiring-map.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/02-mongo-relation.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/03-mongo-polymorphism.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/04-kit-str-value-json.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/05-mongo-index.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/06-mongo-textindex-cleanup.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/plan.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/spec.md is excluded by !projects/**
📒 Files selected for processing (9)
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts
  • packages/1-framework/2-authoring/psl-parser/src/exports/index.ts
  • packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/1-framework/2-authoring/psl-parser/src/exports/index.ts
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Adds JSON and pinned-string PSL combinators. Migrates Mongo attribute interpretation from raw argument parsing to typed AST specifications with source-aware diagnostics for mappings, relations, polymorphism, and indexes.

Changes

Typed PSL parser combinators

Layer / File(s) Summary
JSON and pinned-string parsing
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/*, packages/1-framework/2-authoring/psl-parser/src/exports/index.ts, packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts
Adds json() for non-array JSON objects. Extends str() with exact-value matching, exports, and tests for valid and invalid inputs.

Mongo attribute interpretation

Layer / File(s) Summary
Mongo attribute specifications
packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts, packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
Adds typed attribute specs, AST lookup and interpretation helpers, relation and mapping specs, and index spec builders. Removes superseded raw parsing helpers.
Mapping, polymorphism, and relations
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts, packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts, packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
Uses typed interpretation for mappings, discriminator/base declarations, and relations. Propagates source context and updates diagnostic expectations.
Typed index interpretation
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts, packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts
Interprets index attributes through typed specs, normalizes fields and options, and derives collation and weights. Tests separate indexes and syntax diagnostics.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to e4914

The PR is merge-ready after normal checks and review; no actionable merge-blocking risk remains.

Suggested reviewers: sevinf

Sequence Diagram(s)

sequenceDiagram
  participant PSLModel
  participant AttributeSpecInterpreter
  participant MongoInterpreter
  participant Diagnostics
  PSLModel->>AttributeSpecInterpreter: provide attribute AST nodes
  AttributeSpecInterpreter->>MongoInterpreter: return typed attribute values
  MongoInterpreter->>Diagnostics: append source-aware parse failures
  MongoInterpreter->>PSLModel: produce mappings, relations, polymorphism, and indexes
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: migrating Mongo family attributes to declarative specs.
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2956-mongo-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.

@github-actions

github-actions Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
postgres / no-emit 174.86 KB (0%)
postgres / emit 152.08 KB (0%)
mongo / no-emit 101.09 KB (0%)
mongo / emit 90.95 KB (0%)
cf-worker / no-emit 198.74 KB (0%)
cf-worker / emit 173.36 KB (-0.01% 🔽)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts (1)

176-183: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

indexFieldElement allocates one funcCall arm per model field on every call.

Each buildIndexModelSpec/buildTextIndexModelSpec invocation rebuilds the full arm list, and interpreter.ts calls these inside the per-attribute loop, so a model with F fields and A index attributes builds F×A arms. Memoizing the element (or the spec pair) per model would keep it O(F).

🤖 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-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts`
around lines 176 - 183, The index field arm list is rebuilt for every attribute
because indexFieldElement creates one funcCall per model field on each
invocation. Memoize the resulting indexFieldElement or associated spec pair per
model and reuse it across buildIndexModelSpec/buildTextIndexModelSpec calls,
preserving the existing arms and behavior while reducing construction to O(F).
packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts (1)

1581-1638: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Repeated find-then-assert block could be a helper.

The find(d => d.code === 'PSL_INVALID_ATTRIBUTE_SYNTAX') + toBeDefined() + toMatch(/Expected one of/) triple appears four times here (and again in the polymorphism suite). A small expectSyntaxDiagnostic(result, /Expected one of/) helper would shrink each case to a line.

🤖 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-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts`
around lines 1581 - 1638, Extract the repeated syntax-diagnostic lookup and
assertions into a shared expectSyntaxDiagnostic helper, using the existing
result type and a message pattern parameter. Replace the duplicated find,
toBeDefined, and toMatch blocks in these tests and the polymorphism suite with
calls to the helper, preserving the PSL_INVALID_ATTRIBUTE_SYNTAX code and
Expected one of checks.
packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts (1)

552-565: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

A model field literally named wildcard is misread as a wildcard element.

normalizeIndexField branches on element.fn === 'wildcard' before the sorted-field arm, so @@index([wildcard(sort: Desc)]) on a model that declares a field wildcard yields { name: '$**', isWildcard: true } instead of a descending key on that field. Narrow edge case, but a name check against the model's field names would disambiguate.

🤖 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-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around
lines 552 - 565, Update normalizeIndexField to distinguish the wildcard function
from a model field named “wildcard” by checking the model’s declared field names
before taking the wildcard branch. Preserve the wildcard scope handling for
actual wildcard elements, while treating the field-name case as a sorted field
and retaining its Desc direction.
packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts (2)

87-125: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the diagnostic code in every rejection case.

These tests only check that a failure exists for several invalid inputs, so they would pass even if the parser returned the wrong diagnostic. The PR contract requires PSL_INVALID_ATTRIBUTE_SYNTAX; assert that code in each rejection branch.

Suggested assertion
if (!result.ok) {
  expect(result.failure).toHaveLength(1);
+ expect(result.failure[0]?.code).toBe('PSL_INVALID_ATTRIBUTE_SYNTAX');
}

Also applies to: 323-383

🤖 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/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts`
around lines 87 - 125, Update the rejection branches in the tests around
str('hashed'), including the additional cases at the referenced later range, to
assert that the single failure has code PSL_INVALID_ATTRIBUTE_SYNTAX. Preserve
the existing failure-length checks while adding the diagnostic-code assertion
for every invalid input case.

87-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Place the new *.test.ts coverage alongside the source files.

These additions remain in test/, but the repository guideline requires *.test.ts files to be colocated with their source modules. Move this coverage beside the combinator implementation.

As per coding guidelines, test files matching *.test.ts should be placed alongside source files.

Also applies to: 323-383

🤖 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/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts`
around lines 87 - 125, Move the new combinator coverage from the test directory
to the source directory alongside the combinator implementation, preserving the
existing filename pattern and all test cases. Apply the same relocation to the
additional coverage referenced in the comment, and update any imports or test
configuration references required by the move.

Source: Coding guidelines

packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts (1)

8-11: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use doc comments for both new exported combinators.

Both public APIs are described with ordinary // headers instead of /** ... */ documentation comments.

  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts#L8-L11: convert the json() header to JSDoc.
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts#L7-L10: convert the str() header to JSDoc.
🤖 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/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts`
around lines 8 - 11, Convert the header comments immediately preceding the
exported json() and str() combinators into JSDoc comments, preserving their
existing descriptions and examples. Apply the change in
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts
lines 8-11 and
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts
lines 7-10.

Source: Coding guidelines

🤖 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-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 136-181: Prevent repeated interpretation of malformed `@map` and
@@map attributes from appending duplicate diagnostics. Update
resolveFieldMappings and resolveCollectionName usage so each model’s field
mappings and collection name are computed once and reused across the main loop,
relation FK handling, collectPolymorphismDeclarations, and resolvePolymorphism,
or memoize those resolutions per model while preserving first-resolution
diagnostic emission.

---

Nitpick comments:
In
`@packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts`:
- Around line 8-11: Convert the header comments immediately preceding the
exported json() and str() combinators into JSDoc comments, preserving their
existing descriptions and examples. Apply the change in
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts
lines 8-11 and
packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts
lines 7-10.

In
`@packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts`:
- Around line 87-125: Update the rejection branches in the tests around
str('hashed'), including the additional cases at the referenced later range, to
assert that the single failure has code PSL_INVALID_ATTRIBUTE_SYNTAX. Preserve
the existing failure-length checks while adding the diagnostic-code assertion
for every invalid input case.
- Around line 87-125: Move the new combinator coverage from the test directory
to the source directory alongside the combinator implementation, preserving the
existing filename pattern and all test cases. Apply the same relocation to the
additional coverage referenced in the comment, and update any imports or test
configuration references required by the move.

In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 552-565: Update normalizeIndexField to distinguish the wildcard
function from a model field named “wildcard” by checking the model’s declared
field names before taking the wildcard branch. Preserve the wildcard scope
handling for actual wildcard elements, while treating the field-name case as a
sorted field and retaining its Desc direction.

In
`@packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts`:
- Around line 176-183: The index field arm list is rebuilt for every attribute
because indexFieldElement creates one funcCall per model field on each
invocation. Memoize the resulting indexFieldElement or associated spec pair per
model and reuse it across buildIndexModelSpec/buildTextIndexModelSpec calls,
preserving the existing arms and behavior while reducing construction to O(F).

In `@packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts`:
- Around line 1581-1638: Extract the repeated syntax-diagnostic lookup and
assertions into a shared expectSyntaxDiagnostic helper, using the existing
result type and a message pattern parameter. Replace the duplicated find,
toBeDefined, and toMatch blocks in these tests and the polymorphism suite with
calls to the helper, preserving the PSL_INVALID_ATTRIBUTE_SYNTAX code and
Expected one of checks.
🪄 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 Plus

Run ID: c1650314-8387-4fe3-93b8-6d89e77e18e2

📥 Commits

Reviewing files that changed from the base of the PR and between a50a762 and e78cc55.

⛔ Files ignored due to path filters (8)
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/01-mongo-wiring-map.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/02-mongo-relation.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/03-mongo-polymorphism.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/04-kit-str-value-json.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/05-mongo-index.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/dispatches/06-mongo-textindex-cleanup.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/plan.md is excluded by !projects/**
  • projects/typed-attribute-parsers/slices/mongo-attributes/spec.md is excluded by !projects/**
📒 Files selected for processing (9)
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/json.ts
  • packages/1-framework/2-authoring/psl-parser/src/attribute-spec/combinators/str.ts
  • packages/1-framework/2-authoring/psl-parser/src/exports/index.ts
  • packages/1-framework/2-authoring/psl-parser/test/attribute-spec-combinators.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/mongo-attribute-specs.ts
  • packages/2-mongo-family/2-authoring/contract-psl/src/psl-helpers.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts

Comment on lines +136 to +181
function resolveFieldMappings(input: {
readonly model: ModelSymbol;
readonly sourceFile: SourceFile;
readonly sourceId: string;
readonly diagnostics: ContractSourceDiagnostic[];
}): FieldMappings {
const { model, sourceFile, sourceId, diagnostics } = input;
const pslNameToMapped = new Map<string, string>();
for (const field of Object.values(model.fields)) {
const mapped = getMapName(field.attributes) ?? field.name;
const mapNode = findFieldAttributeNode(field, 'map');
const mapped =
(mapNode
? interpretFieldAttribute({
node: mapNode,
spec: mapFieldSpec,
model,
field,
sourceFile,
sourceId,
diagnostics,
})?.name
: undefined) ?? field.name;
pslNameToMapped.set(field.name, mapped);
}
return { pslNameToMapped };
}

function resolveCollectionName(model: ModelSymbol): string {
return getMapName(model.attributes) ?? lowerFirst(model.name);
function resolveCollectionName(input: {
readonly model: ModelSymbol;
readonly sourceFile: SourceFile;
readonly sourceId: string;
readonly diagnostics: ContractSourceDiagnostic[];
}): string {
const { model, sourceFile, sourceId, diagnostics } = input;
const mapNode = findModelAttributeNode(model, 'map');
const name = mapNode
? interpretModelAttribute({
node: mapNode,
spec: mapModelSpec,
model,
sourceFile,
sourceId,
diagnostics,
})?.name
: undefined;
return name ?? lowerFirst(model.name);

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Repeated @map interpretation now duplicates diagnostics.

resolveFieldMappings/resolveCollectionName push parse failures into diagnostics on every call, and both are invoked several times for the same model: the main loop (Lines 1128-1139), the relation FK branch for target models (Line 1177), collectPolymorphismDeclarations (Line 258), and resolvePolymorphism (Lines 321, 414). A single malformed @map/@@map therefore emits the same diagnostic two or more times (the polymorphism copies land in a separate array that is concatenated at Line 1368). The old getMapName path was diagnostic-free, so this is new noise plus redundant re-interpretation.

Consider computing mappings/collection names once per model up front and threading the results, or memoizing by model with diagnostics emitted only on first resolution.

🤖 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-mongo-family/2-authoring/contract-psl/src/interpreter.ts` around
lines 136 - 181, Prevent repeated interpretation of malformed `@map` and @@map
attributes from appending duplicate diagnostics. Update resolveFieldMappings and
resolveCollectionName usage so each model’s field mappings and collection name
are computed once and reused across the main loop, relation FK handling,
collectPolymorphismDeclarations, and resolvePolymorphism, or memoize those
resolutions per model while preserving first-resolution diagnostic emission.

SevInf added 16 commits August 26, 2026 09:21
…+ dispatch plan)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…@map/@@Map)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…attribute kit

Land the Mongo-side wiring for the declarative attribute-spec kit by adding
mongo-attribute-specs.ts (mirroring the SQL family, family-agnostic, no
cross-family import) and migrating @map/@@Map end-to-end through
interpretAttribute.

- resolveFieldMappings/resolveCollectionName now take { model, sourceFile,
  sourceId, diagnostics } and interpret the map spec, draining failures into
  diagnostics.
- Thread sourceFile/sourceId/diagnostics into all call sites, including
  collectPolymorphismDeclarations and resolvePolymorphism.
- Variant presence check uses getAttribute instead of getMapName.
- Delete the now-dead getMapName helper (getAttribute/stripQuotes retained).

Behaviour is byte-identical for @map/@@Map; existing suite + fixtures:check
are the primary signal.

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
@unique presence-only)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
… spec)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Replace the hand-written parseRelationAttribute string extraction with a
declarative relationFieldSpec (name/fields/references, no refine) interpreted
through interpretFieldAttribute, mirroring the SQL family. fieldRef adds
field-existence validation the old parser lacked: a @relation naming a
non-existent field now emits PSL_INVALID_ATTRIBUTE_SYNTAX. Valid schemas lower
byte-identically. Retire parseRelationAttribute/ParsedRelationAttribute and the
now-dead stripQuotes helper; keep parseFieldList.

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
@base to specs)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
… specs

Replace the imperative getPositionalArgument/parseQuotedStringLiteral
parsing in collectPolymorphismDeclarations with findModelAttributeNode +
interpretModelAttribute against new discriminatorModelSpec/baseModelSpec,
copied from the SQL templates. Argument-shape errors (missing arg,
non-quoted value, non-existent discriminator field) now surface as
grammar PSL_INVALID_ATTRIBUTE_SYNTAX; the discriminator-field-must-be-
String check stays a semantic PSL_INVALID_ATTRIBUTE_ARGUMENT.

resolvePolymorphism semantics are unchanged. getPositionalArgument and
parseQuotedStringLiteral remain defined in psl-helpers for the index
attributes.

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…mongo index surface)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Add two leaf combinators to the attribute-spec kit for the Mongo index
argument surface (wired in a later dispatch):

- str(value): a pinned string-literal overload of str(), mirroring
  num()/num(value). Pins to a single literal (e.g. str("hashed")) for
  digit-leading index type tokens that cannot be bare identifiers.
- json(): reads an opaque JSON object from a quoted, parser-decoded JSON
  string, matching the interpreter parseJsonArg behaviour (non-array
  object only). The single JSON.parse-of-unknown narrowing is a justified
  blindCast; no bare as.

Both additions are additive: the unpinned str() and all existing
psl-parser/sql/mongo tests stay green with no edits. Adds focused unit
tests for both combinators.

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
… to specs)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…o attribute specs

Route model-level @@index and @@unique argument parsing through
interpretModelAttribute + a new buildIndexModelSpec, replacing the imperative
getNamedArgument/parse* helpers. The dense index-shape validation
(PSL_INVALID_INDEX in all forms, the collation-locale-required rule), the
PSL_INDEX_FIELD_NOT_FOUND existence check, key-building, and MongoIndex
construction are unchanged; only the argument source moves onto specs. Lowering
is byte-identical for valid schemas.

buildIndexModelSpec composes a per-model field element
(oneOf(fieldRef, wildcard(scope?), field(sort:))) plus the full named-arg
surface (type/sparse/expireAfterSeconds/filter[json]/include/exclude[str]/
default_language/languageOverride + 9 collation args). @@textIndex stays on its
existing pre-spec branch (migrated in a later dispatch).

Per operator Option A, argument-shape errors now surface as
PSL_INVALID_ATTRIBUTE_SYNTAX: a field reference absent from the model is
rejected at the grammar layer by fieldRef, so PSL_INDEX_FIELD_NOT_FOUND now
guards only present-but-not-indexable (relation) fields. parseIndexDirection is
removed (its sole caller moved to the spec path; @@textIndex never used it).

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
…delete legacy parsers)

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Add buildTextIndexModelSpec and route @@textIndex through the spec
interpreter like @@index/@@unique, filling the same normalized locals via
a cast-free two-branch (isTextIndex) structure since the two specs infer
different named-arg shapes. Weights are number-filtered via a new
extractWeights helper (typeof-narrowed, no cast).

This orphans the pre-spec argument parsers, so delete them (biome
noUnusedVariables): parseCollation, parseNumericArg, parseBooleanArg,
parseJsonArg, stripQuotesHelper (interpreter.ts) and parseIndexFieldList,
parseIndexFieldSegment, parseFieldList, splitTopLevel, getNamedArgument,
getPositionalArgument (psl-helpers.ts). Keep parseProjectionList,
getAttribute, lowerFirst, parseQuotedStringLiteral, ParsedIndexField.

Reword the comments naming the removed parseIndexDirection/parseCollation.
Per Option A, @@textIndex now rejects undeclared args and shifts
undeclared-field references to PSL_INVALID_ATTRIBUTE_SYNTAX (via fieldRef);
update the one shifted assertion. Contracts stay byte-identical for valid
schemas.

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
The bare `as Contract['storage']` cast tripped scripts/lint-no-contract-cast.mjs,
failing CI's Lint job. Replace it with blindCast<T, Reason>, an identity
re-type, removing the as-Contract smell and one bare as.

Signed-off-by: Serhii Tatarintsev <tatarintsev@prisma.io>
Signed-off-by: Steven McClankerton <tatarintsev@prisma.io>
@SevInf
SevInf force-pushed the tml-2956-mongo-attributes branch from e78cc55 to e491496 Compare August 26, 2026 09:44
@coderabbitai

coderabbitai Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@pkg-pr-new

pkg-pr-new Bot commented Aug 26, 2026

Copy link
Copy Markdown

Open in StackBlitz

@prisma/orm-extension-arktype-json

npm i https://pkg.pr.new/@prisma/orm-extension-arktype-json@29833

@prisma/orm-extension-middleware-cache

npm i https://pkg.pr.new/@prisma/orm-extension-middleware-cache@29833

@prisma/orm-extension-paradedb

npm i https://pkg.pr.new/@prisma/orm-extension-paradedb@29833

@prisma/orm-extension-pgvector

npm i https://pkg.pr.new/@prisma/orm-extension-pgvector@29833

@prisma/orm-extension-postgis

npm i https://pkg.pr.new/@prisma/orm-extension-postgis@29833

@prisma/orm-extension-supabase

npm i https://pkg.pr.new/@prisma/orm-extension-supabase@29833

@prisma/orm-family-mongo

npm i https://pkg.pr.new/@prisma/orm-family-mongo@29833

@prisma/orm-family-sql

npm i https://pkg.pr.new/@prisma/orm-family-sql@29833

@prisma/orm-framework

npm i https://pkg.pr.new/@prisma/orm-framework@29833

@prisma/orm-mongo

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

@prisma/orm-postgres

npm i https://pkg.pr.new/@prisma/orm-postgres@29833

@prisma/orm-sqlite

npm i https://pkg.pr.new/@prisma/orm-sqlite@29833

@prisma/orm-target-mongo

npm i https://pkg.pr.new/@prisma/orm-target-mongo@29833

@prisma/orm-target-postgres

npm i https://pkg.pr.new/@prisma/orm-target-postgres@29833

@prisma/orm-target-sqlite

npm i https://pkg.pr.new/@prisma/orm-target-sqlite@29833

@prisma/orm-toolchain

npm i https://pkg.pr.new/@prisma/orm-toolchain@29833

commit: e491496

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants