Repository navigation
feat(sql): timestamp authoring via temporal.* preset surface (Postgres + SQLite) - #422
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds phase-aware execution defaults (onCreate/onUpdate) across authoring, PSL, TS contract, targets, and runtime; introduces temporal authoring presets and a canonical ChangesPhase-Aware Execution Defaults & temporal timestamp support
sequenceDiagram
participant PSL as PSL_Schema
participant Interpreter as PSL_Interpreter
participant Resolver as Field_Resolver
participant Builder as Contract_Builder
participant Runtime as Target_Runtime
PSL->>Interpreter: parse schema with temporal defaults/attributes
Interpreter->>Resolver: emit field descriptors (attributes/presets)
Resolver->>Resolver: resolve presets, validate phases, produce executionDefaults
Resolver->>Builder: lower fields including storage defaults or executionDefaults (onCreate/onUpdate)
Builder->>Runtime: build contract.execution.mutations.defaults with refs
Runtime->>Runtime: createExecutionContext -> assert generators available
Runtime->>Runtime: applyMutationDefaults(op, values, acrossRowsCache?)
alt op == create
Runtime->>Runtime: run onCreate -> timestampNow.generate() -> Date
else op == update and values non-empty
Runtime->>Runtime: run onUpdate -> timestampNow.generate() -> Date
else op == update and values empty
Runtime-->>Runtime: skip onUpdate defaults
end
🎯 4 (Complex) | ⏱️ ~60 minutes
✨ Finishing Touches🧪 Generate unit tests (beta)
|
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@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/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: |
Adds phase-specific execution defaults to SQL TS authoring so generated IDs stay on-create-only while updatedAt can use both create and update phases. Wires Prisma-compatible @updatedat lowering for Postgres and SQLite PSL, plus field.updatedAt() helpers backed by target-owned timestampNow generators. Empty update payloads skip onUpdate defaults so no-op updates do not advance updatedAt.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/1-framework/1-core/framework-components/test/framework-components.authoring.test.ts (1)
348-389: ⚡ Quick winUse distinct values for
createandupdateto catch path-routing bugs.Both paths (
['create']and['update']) resolve to the same{ kind: 'generator', id: 'timestampNow' }, so a bug that silently maps both phases to the same path would still pass. Distinct values pin the expected output to the correct source path.♻️ Proposed fix: use distinct generator ids per phase
- expect( - instantiateAuthoringFieldPreset(descriptor, [ - { - create: { kind: 'generator', id: 'timestampNow' }, - update: { kind: 'generator', id: 'timestampNow' }, - }, - ]), - ).toEqual({ - descriptor: { - codecId: 'test/timestamp@1', - nativeType: 'timestamp', - }, - nullable: false, - executionDefaults: { - onCreate: { kind: 'generator', id: 'timestampNow' }, - onUpdate: { kind: 'generator', id: 'timestampNow' }, - }, - id: false, - unique: false, - }); + expect( + instantiateAuthoringFieldPreset(descriptor, [ + { + create: { kind: 'generator', id: 'timestampCreate' }, + update: { kind: 'generator', id: 'timestampUpdate' }, + }, + ]), + ).toEqual({ + descriptor: { + codecId: 'test/timestamp@1', + nativeType: 'timestamp', + }, + nullable: false, + executionDefaults: { + onCreate: { kind: 'generator', id: 'timestampCreate' }, + onUpdate: { kind: 'generator', id: 'timestampUpdate' }, + }, + id: false, + unique: false, + });🤖 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/1-core/framework-components/test/framework-components.authoring.test.ts` around lines 348 - 389, The test uses identical values for create and update so it won't catch path-routing bugs; change the test data passed to instantiateAuthoringFieldPreset so the create and update inputs differ (e.g., use distinct generator ids) and update the expected executionDefaults accordingly; specifically modify the descriptor.executionDefaults onCreate/onUpdate and the argument object with keys create/update used in the call to instantiateAuthoringFieldPreset so the resulting executionDefaults.onCreate and .onUpdate are different, ensuring instantiateAuthoringFieldPreset (and its handling of executionDefaults) is validated.
🤖 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
`@packages/1-framework/1-core/framework-components/test/framework-components.authoring.test.ts`:
- Around line 348-389: The test uses identical values for create and update so
it won't catch path-routing bugs; change the test data passed to
instantiateAuthoringFieldPreset so the create and update inputs differ (e.g.,
use distinct generator ids) and update the expected executionDefaults
accordingly; specifically modify the descriptor.executionDefaults
onCreate/onUpdate and the argument object with keys create/update used in the
call to instantiateAuthoringFieldPreset so the resulting
executionDefaults.onCreate and .onUpdate are different, ensuring
instantiateAuthoringFieldPreset (and its handling of executionDefaults) is
validated.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 7ed225dd-4977-4e25-b5ea-57774b938505
⛔ Files ignored due to path filters (2)
projects/created-updated-at-authoring/plan.mdis excluded by!projects/**projects/created-updated-at-authoring/spec.mdis excluded by!projects/**
📒 Files selected for processing (29)
docs/products/psl/README.mdpackages/1-framework/1-core/framework-components/src/shared/framework-authoring.tspackages/1-framework/1-core/framework-components/test/framework-components.authoring.test.tspackages/2-sql/2-authoring/contract-psl/README.mdpackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.defaults.test.tspackages/2-sql/2-authoring/contract-psl/test/ts-psl-parity.test.tspackages/2-sql/2-authoring/contract-ts/API.mdpackages/2-sql/2-authoring/contract-ts/README.mdpackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/src/contract-definition.tspackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tspackages/2-sql/2-authoring/contract-ts/src/contract-lowering.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.contract-definition.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.tspackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/5-runtime/test/sql-context.test.tspackages/3-targets/3-targets/postgres/src/core/authoring.tspackages/3-targets/3-targets/sqlite/src/core/authoring.tspackages/3-targets/3-targets/sqlite/src/core/descriptor-meta.tspackages/3-targets/6-adapters/postgres/src/core/control-mutation-defaults.tspackages/3-targets/6-adapters/postgres/src/exports/runtime.tspackages/3-targets/6-adapters/postgres/test/control-mutation-defaults.test.tspackages/3-targets/6-adapters/sqlite/src/core/control-mutation-defaults.tspackages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.tspackages/3-targets/6-adapters/sqlite/test/control-mutation-defaults.test.ts
Reject @updatedat before relation fields are discarded so invalid PSL cannot be accepted silently. Keep the adapter mutation default descriptors contextually typed and narrow optional runtime generator hooks in tests so package typechecks remain green.
Resolves todos/056 (P1) and todos/057 (P1) from the PR #422 review. The phased mutation-default shape `executionDefaults: { onCreate?, onUpdate? }` was added in 682714e alongside the legacy single-slot `executionDefault?`. The legacy slot is `{ onCreate: X }` in disguise, so carrying both forces a runtime guard, a dynamic property-name label, and duplicated default+nullable validation across every layer (FieldNode, ValueObjectFieldNode, AuthoringFieldPresetOutput, ScalarFieldState, ResolvedField). It also sets a precedent that adding onDelete later requires another conditional in the reconciler. Changes: - Drop `executionDefault` from FieldNode, ValueObjectFieldNode, AuthoringFieldPresetOutput, ScalarFieldState, AnyScalarFieldState, and ResolvedField. - Every site that produced the singular form now wraps as `executionDefaults: { onCreate: X }`. Affects field.generated, the family-sql id helper presets (uuidv4, uuidv7, ulid, nanoid, cuid2, ksuid), and PSL `lowerDefaultForField`. - Delete `resolveExecutionDefaultPhases` and the dynamic `executionDefaultProperty` branch from build-contract.ts. The loop body checks `field.executionDefaults` directly. - Loosen the nullable check (todo 057): only fire when `onCreate` is set. An `onUpdate`-only mutation default is fine on a nullable field — it can legitimately start as NULL until first update. New regression test: `allows nullable fields with onUpdate-only executionDefaults`. - PSL `psl-field-resolution.ts` now combines `loweredDefault.executionDefaults` (on-create from generated `@default(...)`) and `updatedAtExecutionDefaults` (both phases from `@updatedAt`) via `??`. The two are mutually exclusive — `lowerUpdatedAtAttribute` rejects `@updatedAt @default(...)`. Net change: -33 lines across 13 files. One validator function gone, one runtime guard gone, one dynamic property-name label branch gone. Validation: - pnpm typecheck (123/123 tasks) - pnpm lint:deps (clean) - @prisma-next/framework-components test: 131/131 - @prisma-next/sql-contract-ts test: 218/218 - @prisma-next/sql-contract-psl test: 115/115 - @prisma-next/family-sql test: 285/285 - @prisma-next/adapter-postgres test: 615/615 - @prisma-next/adapter-sqlite test: 110/110
…agnostic (todos 061, 066) - Extract `rejectUpdatedAtOnNonScalar` helper in `psl-field-resolution.ts` and call it from the two upstream relation/list-field early-return sites instead of duplicating the inline diagnostic. Scalar-field rules continue to live in `lowerUpdatedAtAttribute` as the authoritative codec gate, while the new helper is the single owner of the relation/list rejection wording. - Pass `targetId` into `lowerUpdatedAtAttribute` and rewrite the `PSL_INVALID_DEFAULT_APPLICABILITY` message raised when the `timestampNow` generator is absent. The message now points users at the responsible target adapter rather than surfacing the SPI-level concept of a mutation default generator. The diagnostic code is unchanged so existing matchers continue to work.
…ext creation (todo 063) Surface RUNTIME.MISSING_MUTATION_DEFAULT_GENERATOR at createExecutionContext time when the contract references generator ids the assembled stack does not provide. Walks contract.execution.mutations.defaults across both onCreate and onUpdate phases, deduplicates missing ids, and throws a single structured error. Aligns with ADR 031/065's startup-time capability negotiation: contracts naming a generator id whose runtime implementation isn't shipped now fail fast at context construction rather than at first applyMutationDefaults call. The existing lazy fallback in computeExecutionDefaultValue (RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING) is retained as defense-in-depth — the new contract-time check supplements it, it does not replace it.
…(todos 058, 059, 060, 064) - 064: export `TIMESTAMP_NOW_GENERATOR_ID` constant and `ExecutionMutationDefaultPhases` type from canonical sources; replace duplicated literals/aliases across PSL/TS authoring and adapters. - 059: add `MutationDefaultGeneratorDescriptor.buildPhases?`; PSL `lowerUpdatedAtAttribute` now delegates phase construction to the generator descriptor (no inline literal). PSL/TS authoring stay byte-equivalent for any future params-bearing generator. - 058: centralize `timestampNow` wiring in `@prisma-next/family-sql` via `timestampNowControlDescriptor(applicableCodecIds)` and `timestampNowRuntimeGenerator()`. Postgres + SQLite adapters opt in rather than re-declare the body. - 060: add `RuntimeMutationDefaultGenerator.applyOnEmptyUpdate?` and switch `applyMutationDefaults` from a global empty-update short-circuit to a per-generator opt-out. Default `false` preserves @updatedat RD2; future onUpdate generators can opt in to sentinel-write semantics. Test counts (post-change): - @prisma-next/framework-components: 133 tests - @prisma-next/sql-contract-ts: 218 tests - @prisma-next/sql-contract-psl: 115 tests (incl. ts-psl-parity unchanged) - @prisma-next/family-sql: 285 tests - @prisma-next/sql-runtime: 186 tests + 1 skipped (incl. new applyOnEmptyUpdate=true regression) - @prisma-next/adapter-postgres: 615 tests - @prisma-next/adapter-sqlite: 110 tests
9bebfba to
40d67af
Compare
… rows The runtime contract already encoded @updatedat as a both-phase execution mutation default (timestampNow generator on onCreate and onUpdate), but only the create path threaded it through applyMutationDefaults. ORM update, updateAll, updateCount, the upsert update branch, and the nested update branch in updateFirstGraph all skipped the call, so a non-empty update never advanced updatedAt. Wire applyMutationDefaults into every update path. Empty payloads still short-circuit before the runtime call, preserving the no-write-no-advance rule. Bulk inserts (createAll/createMany) called applyMutationDefaults per row, which made timestampNow generate a fresh Date per row and drift within a single ORM operation. Add a stableAcrossRows generator flag plus an acrossRowsCache parameter to applyMutationDefaults so bulk operations reuse one generated value across every row that needs the default. Mark timestampNow as stableAcrossRows: true. Per-row generators (cuid, uuidv4, etc.) stay independent because the cache only honors stableAcrossRows generators. Adds runtime-side tests for the cache contract and orm-client tests covering create, createAll, updateAll, updateCount, upsert (both branches), and explicit-value preservation.
…ability Add Milestone 4 to the created-updated-at-authoring plan covering the two compatibility gaps surfaced by comparing against Prisma 6's @updatedat semantics: ORM update paths skipped applyMutationDefaults, and bulk inserts drifted timestampNow per row. Also record the naming choice (stableAcrossRows / acrossRowsCache) under Resolved Decisions so future readers see why it didn't end up as bulkStable.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
packages/3-extensions/sql-orm-client/src/mutation-executor.ts (1)
239-247: ⚡ Quick winConsider deduplicating with
applyUpdateDefaults.This block performs the exact same logic as the new
applyUpdateDefaultshelper incollection.ts(callapplyMutationDefaultsforop: 'update', then merge defaults back intovalues). Extracting a shared helper would keep the two update paths in lockstep if the contract for update defaults evolves (e.g., new opt-ins likeapplyOnEmptyUpdate).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-extensions/sql-orm-client/src/mutation-executor.ts` around lines 239 - 247, This code duplicates the "call applyMutationDefaults for op: 'update' then merge defaults into values" logic now present as applyUpdateDefaults in collection.ts; refactor to reuse that helper: replace the resolveModelTableName + applyMutationDefaults + loop that assigns mappedUpdateData[def.column] = def.value with a call to the shared applyUpdateDefaults helper (importing it from collection.ts), passing contract, modelName/tableName and mappedUpdateData so defaults are applied in one place and both update paths stay in sync (ensure applyUpdateDefaults accepts the same parameters or adapt its signature once centrally).packages/3-extensions/sql-orm-client/src/collection.ts (1)
117-138: 💤 Low valueCache scope nit: bulk-only allocation skips single-row stability.
acrossRowsCacheis only created whenrows.length > 1. Forrows.length === 1, no cache is needed within this call, but if a caller invokesapplyCreateDefaultsmultiple times in a single logical operation with one row per call (see the MTI path), each call produces a fresh value forstableAcrossRows: truegenerators. Consider accepting an optional external cache parameter so callers that span multipleapplyCreateDefaultsinvocations within one mutation can opt into shared stability.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-extensions/sql-orm-client/src/collection.ts` around lines 117 - 138, The current applyCreateDefaults function only allocates acrossRowsCache when rows.length > 1, which prevents stableAcrossRows generators from being stable across multiple applyCreateDefaults calls; modify applyCreateDefaults to accept an optional external acrossRowsCache parameter (e.g. acrossRowsCache?: Map<string, unknown>) and use it when provided (falling back to the existing per-call allocation logic), and pass that cache through to ctx.context.applyMutationDefaults so callers (like the MTI path) can reuse the same Map across multiple invocations to preserve stability for generators marked stableAcrossRows.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts`:
- Around line 311-321: The resolved literal value from
resolveAuthoringTemplateValue(template.value, args) is currently cast to
ColumnDefaultLiteralInputValue without validation; add a runtime predicate
(e.g., isColumnDefaultLiteralInputValue) and use it to validate value before
returning the ColumnDefault literal, throwing a clear Error if the predicate
fails—mirror the pattern used in resolveExecutionMutationDefaultPhase()
(validate with isExecutionMutationDefaultValue then throw) and apply it to the
branch that returns { kind: 'literal', value: ... } so only
JSON-serializable/allowed shapes are emitted.
In `@packages/2-sql/9-family/src/core/timestamp-now-generator.ts`:
- Around line 1-6: timestampNowRuntimeGenerator() is a runtime-plane
implementation and must be moved out of src/core/ to avoid importing runtime
types into the core; move the function into a new runtime file (e.g. create
src/exports/runtime.ts or src/runtime/timestamp-now-generator.ts), adjust its
imports to only reference runtime-plane types (RuntimeMutationDefaultGenerator),
and update the package exports to re-export it; leave
timestampNowControlDescriptor() in src/core/ (remove any runtime imports from
that file) and update any import sites to import the runtime generator from the
new runtime module while keeping the control descriptor in core.
In
`@packages/3-extensions/sql-orm-client/test/collection-mutation-defaults.test.ts`:
- Around line 154-161: The test currently compares Date timestamps which can be
equal for distinct Date instances; update the assertions in the block that uses
planParams(runtime.executions[0]) and dateParams to assert object identity for
the stableAcrossRows behavior: verify that dateParams[0], dateParams[1], and
dateParams[2] are the same object (use strict identity checks like
expect(...).toBe(...)) instead of comparing getTime() values so the test
guarantees the cached Date instance was reused across rows.
---
Nitpick comments:
In `@packages/3-extensions/sql-orm-client/src/collection.ts`:
- Around line 117-138: The current applyCreateDefaults function only allocates
acrossRowsCache when rows.length > 1, which prevents stableAcrossRows generators
from being stable across multiple applyCreateDefaults calls; modify
applyCreateDefaults to accept an optional external acrossRowsCache parameter
(e.g. acrossRowsCache?: Map<string, unknown>) and use it when provided (falling
back to the existing per-call allocation logic), and pass that cache through to
ctx.context.applyMutationDefaults so callers (like the MTI path) can reuse the
same Map across multiple invocations to preserve stability for generators marked
stableAcrossRows.
In `@packages/3-extensions/sql-orm-client/src/mutation-executor.ts`:
- Around line 239-247: This code duplicates the "call applyMutationDefaults for
op: 'update' then merge defaults into values" logic now present as
applyUpdateDefaults in collection.ts; refactor to reuse that helper: replace the
resolveModelTableName + applyMutationDefaults + loop that assigns
mappedUpdateData[def.column] = def.value with a call to the shared
applyUpdateDefaults helper (importing it from collection.ts), passing contract,
modelName/tableName and mappedUpdateData so defaults are applied in one place
and both update paths stay in sync (ensure applyUpdateDefaults accepts the same
parameters or adapt its signature once centrally).
🪄 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: 8499d0a9-fc51-444b-af99-29bff139493c
📒 Files selected for processing (26)
packages/1-framework/0-foundation/contract/src/exports/types.tspackages/1-framework/0-foundation/contract/src/types.tspackages/1-framework/1-core/framework-components/src/exports/control.tspackages/1-framework/1-core/framework-components/src/shared/framework-authoring.tspackages/1-framework/1-core/framework-components/src/shared/mutation-default-types.tspackages/1-framework/1-core/framework-components/test/framework-components.authoring.test.tspackages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-ts/src/contract-definition.tspackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tspackages/2-sql/4-lanes/relational-core/src/query-lane-context.tspackages/2-sql/5-runtime/README.mdpackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/5-runtime/test/mutation-default-generators.test.tspackages/2-sql/5-runtime/test/sql-context.test.tspackages/2-sql/9-family/src/core/timestamp-now-generator.tspackages/2-sql/9-family/src/exports/control.tspackages/2-sql/9-family/src/exports/runtime.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/mutation-executor.tspackages/3-extensions/sql-orm-client/test/collection-mutation-defaults.test.tspackages/3-targets/6-adapters/postgres/src/core/control-mutation-defaults.tspackages/3-targets/6-adapters/postgres/src/exports/runtime.tspackages/3-targets/6-adapters/sqlite/src/core/control-mutation-defaults.tspackages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.ts
✅ Files skipped from review due to trivial changes (1)
- packages/3-targets/6-adapters/postgres/src/core/control-mutation-defaults.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.ts
- packages/1-framework/1-core/framework-components/test/framework-components.authoring.test.ts
- packages/2-sql/2-authoring/contract-psl/test/fixtures.ts
- packages/2-sql/5-runtime/test/sql-context.test.ts
- packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts
Reframe the project around a generic PSL field-preset dispatch path (mirroring the existing TS field-preset registry), exposed as temporal.createdAt() / temporal.updatedAt() in PSL and field.temporal.createdAt() / field.temporal.updatedAt() in TS. The Prisma-flavored @updatedat attribute is removed; codec applicability stops being a user-facing diagnostic and becomes a registry-coherence concern. Contract IR, runtime, and ORM-client work from prior milestones survive untouched (consolidated into "Inherited Foundation"). All open design questions resolved inline; reviewer feedback applied where it didn't conflict with prior decisions.
Adds a generic field-preset dispatch path to PSL, symmetric with the existing type-constructor dispatch. The path resolves namespaced calls in field-type position against authoringContributions.field, instantiates the preset via the same instantiateAuthoringFieldPreset machinery TS uses, and produces default / executionDefaults / id / unique / nullable contributions on the resolved field. Field presets resolve before type constructors (presets carry richer semantics; the more complete answer wins). The temporal namespace is added to the curated-namespaces exemption list, alongside db/family/ target — chosen for forward-compatibility with the JS/TS Temporal API. Preset usage is constrained per spec FR7: optional preset (?), list preset ([]), preset + @default, preset + @id, and preset + @updatedat are all hard errors with stable diagnostic codes. PSL → typed-args coercion happens in instantiatePslFieldPreset via mapPslHelperArgs; instantiateAuthoringFieldPreset itself stays typed-input-only. Test fixture proves genericness via a synthetic temporal.exampleField() preset (not a temporal-specific code path).
…sion check Adds defense-in-depth and user-facing diagnostics that close out Phase A of the field-preset pivot: PSL preset-misuse diagnostics: - PSL_PRESET_NOT_OPTIONAL — `temporal.X()?` rejected (preset is a complete declaration; system owns the value, optional contradicts that). - PSL_PRESET_NOT_LIST — `temporal.X()[]` rejected (presets aren't list elements). - PSL_PRESET_AND_DEFAULT_CONFLICT — `temporal.X() @default(...)` rejected (preset already specifies its own defaults). - PSL_PRESET_AND_ID_CONFLICT — `temporal.X() @id` rejected when the preset doesn't itself contribute id semantics. - PSL_PRESET_AND_UPDATED_AT_CONFLICT — `temporal.X() @updatedAt` rejected (preset already specifies execution defaults). - PSL_UNKNOWN_FIELD_PRESET — typo in a curated namespace surfaces a spelling-targeted hint instead of falling through to the generic PSL_UNSUPPORTED_FIELD_TYPE. Compose-time registry collision check: - createComposedAuthoringHelpers now rejects any path registered as both a field preset and a type constructor with a clear "Ambiguous authoring registry path" error. Belt-and-suspenders to RD9's runtime field-preset- first ordering — the error surfaces at composition, not at PSL resolution. Tests: - Five preset-misuse cases in interpreter.defaults.test.ts. - Cross-registry collision case in authoring-helper-runtime.test.ts. Validation gate (all green): - @prisma-next/sql-contract-psl: 121 tests - @prisma-next/sql-contract-ts: 219 tests - @prisma-next/framework-components: 133 tests - pnpm lint:deps: 716 modules, 0 violations
The original RD11 said to rename PSL_INVALID_TYPE_CONSTRUCTOR_ARITY → PSL_INVALID_NAMESPACED_CALL_ARITY. Phase A revealed the assumption was wrong: that code name doesn't exist. Type-constructor arity/arg errors today emit PSL_INVALID_ATTRIBUTE_ARGUMENT (a code shared with genuine attribute-arg errors like @id(badarg)). The honest rename to a PSL_INVALID_NAMESPACED_CALL_ARGUMENT code would need to disambiguate those cases too, which is a wider refactor than this project warrants. Decision: field-preset arity/arg errors emit PSL_INVALID_ATTRIBUTE_ARGUMENT for now, matching the existing type-constructor pattern. Honest rename deferred to a follow-up. This commit: - Updates FR7 to enumerate diagnostic codes that match what's actually implemented, with notes on which cases are tested in Phase A vs deferred. - Marks AC5 sub-items by implementation status (a, b, d, e, h, j shipped with tests; c, f, g, i deferred or covered indirectly). - Adds AC5j for the transient PSL_PRESET_AND_UPDATED_AT_CONFLICT code that disappears in Phase C alongside the @updatedat attribute path. - Rewrites RD11 to reflect the discovery and the deferral decision. - Updates plan.md task list and Resolved Decisions consistently.
Moves the createdAt/updatedAt field-preset registrations from flat
target.authoring.field.{createdAt,updatedAt} to nested
target.authoring.field.temporal.{createdAt,updatedAt} for both Postgres
and SQLite targets. The TS surface follows: field.createdAt() /
field.updatedAt() → field.temporal.createdAt() / field.temporal.updatedAt().
PSL was already wired in Phase A — temporal.createdAt() /
temporal.updatedAt() now resolve through the field-preset dispatch path
once the registry move lands here.
Updates to keep parity with the new namespace:
- Test fixtures: contract-builder.dsl.helpers.test.ts,
ts-psl-parity.test.ts (sqliteTimestampTargetPack,
postgresTimestampTargetPack, sqlFamilyPack).
- Examples: react-router-demo and prisma-next-demo TS contracts.
- CLI init templates (TS template) + snapshot.
- Integration type tests.
- Doc comments in mutation-default-types.ts and timestamp-now-generator.ts.
PSL examples (.prisma) and the @updatedat attribute path are unchanged
in Phase B — they ship intact through Phase C, which deletes the
attribute and updates PSL examples to use temporal.updatedAt().
Validation gate (all green):
- pnpm test:packages: 110/110 turbo tasks
- pnpm lint:deps: 716 modules, 0 violations
Deletes the Prisma-flavored @updatedat attribute path that landed on this branch in commit 682714e. The codec-applicability validation that motivated the pivot is gone; users now write temporal.updatedAt() in PSL and field.temporal.updatedAt() in TS, both consuming the same field-preset registry shipped in Phases A+B. What's deleted from psl-field-resolution.ts (~110 lines): - 'updatedAt' entry in BUILTIN_FIELD_ATTRIBUTE_NAMES - reportInvalidUpdatedAt, rejectUpdatedAtOnNonScalar (helpers) - lowerUpdatedAtAttribute (the codec-applicability path) - The relation-field @updatedat rejection branches in collectResolvedFields - The @updatedat lowering merge with @default(generator()) - The PSL_PRESET_AND_UPDATED_AT_CONFLICT branch (no longer reachable once the attribute is gone) Migration hint: - New helper getRemovedAttributeHint() returns a per-attribute suggestion. Currently has one entry: 'updatedAt' → 'Use `temporal.updatedAt()` as a field-preset call instead.' - The hint is appended to the standard PSL_UNSUPPORTED_FIELD_ATTRIBUTE message when the attribute name matches and the field doesn't already declare a temporal.* preset (suppression check). - Implementation is the requested hardcoded if-branch — no map. Adding more migrations later means adding another branch. Tests: - Replaced four @updatedAt-attribute tests in interpreter.defaults with temporal.updatedAt()-preset tests (Postgres + SQLite, plus inline preset registrations matching the production target shape). - Added two new tests: migration-hint emission, and hint suppression for already-migrated fields (the `temporal.updatedAt() @updatedAt` half-migrated case). - Removed the obsolete PSL_PRESET_AND_UPDATED_AT_CONFLICT test. - Updated the PSL parity test (sqlite + postgres) to use temporal.updatedAt() PSL syntax. Diagnostic-code inventory (per RD11): grep confirmed PSL_INVALID_DEFAULT_APPLICABILITY remains in use elsewhere (storage default lowering); PSL_PRESET_AND_UPDATED_AT_CONFLICT is now orphaned and removed. Doc-comment updates in: - packages/1-framework/1-core/framework-components/src/shared/mutation-default-types.ts - packages/3-extensions/sql-orm-client/src/collection.ts Spec/plan updates: - AC4 marked complete; references PSL_UNSUPPORTED_FIELD_ATTRIBUTE (the actual code) instead of the spec's earlier PSL_UNKNOWN_ATTRIBUTE (which doesn't exist). - AC5j superseded note: half-migrated fields now use the suppression path instead of a dedicated diagnostic. Validation gate: 120 PSL tests pass, full lint:deps clean (716 modules, 0 violations). adapter-postgres (615) and target-mongo (447) pass standalone; turbo-aggregate flake unrelated to this commit. BREAKING CHANGE: PSL @updatedat is no longer a recognized attribute. Migrate to `temporal.updatedAt()` field-preset syntax. The unknown- attribute diagnostic includes the migration hint inline.
Update existing references to the renamed/removed surfaces: - docs/products/psl/README.md — timestamp section now lists temporal.createdAt() / temporal.updatedAt() as the preset surface alongside @default(now()), and notes that @updatedat is no longer recognized (with the migration-hint diagnostic). - packages/2-sql/2-authoring/contract-psl/README.md — Responsibilities bullet and "Supported timestamp authoring surface" section. - packages/2-sql/2-authoring/contract-ts/{README.md,API.md} — bulk rename field.createdAt() / field.updatedAt() → field.temporal.createdAt() / field.temporal.updatedAt() across helper-vocabulary lists, code examples, and timestamp-helper notes. Scope-bounded: only updates pre-existing references — no restructuring, no new sections, no docs that weren't already in the inventory. Validation: 110/110 turbo tasks (adapter-postgres flake confirmed unrelated by standalone re-run, 615 tests pass), lint:deps 716 modules / 0 violations.
…gets
Hoist the `temporal.{createdAt,updatedAt}` field-preset descriptors into a
single `temporalAuthoringPresets({ codecId, nativeType })` helper exported
from `@prisma-next/family-sql/control`. Postgres and SQLite each pass only
their target-specific codec/native-type pair; the rest of the descriptor
(default expression, generator id, both phases) is owned by the helper, so
PSL `temporal.updatedAt()` and TS `field.temporal.updatedAt()` lower to
byte-identical contracts across targets by construction.
Also drops the unused flat `dateTime` preset from SQLite authoring — it had
no callers in `packages/`, `examples/`, or tests, and was a parity wart
relative to Postgres' pre-existing flat `dateTime`. The Postgres flat
`dateTime` is left untouched since it predates this branch.
The `applyOnEmptyUpdate?: boolean` flag on `RuntimeMutationDefaultGenerator`
was added as a forward-compat hook for hypothetical future generators that
want sentinel-write semantics on empty update payloads. No production
generator opts in; the only caller was a self-test of the flag itself.
Per CLAUDE.md ("Don't design for hypothetical future requirements"), drop
the flag, the runtime branch in `applyMutationDefaults`, and the self-test.
Empty-update skip is now unconditional. Re-add when a real generator needs
sentinel semantics, with a test exercising real production code.
RD2 ("empty update payloads skip onUpdate defaults") is still enforced —
just simpler now.
`build-contract.ts` previously allowed nullable fields when only
`executionDefaults.onUpdate` was present (no `onCreate`), reasoning that
the column could start NULL until first update. That branch was a
forward-compat hook for hypothetical onUpdate-only presets — dead code with
respect to `temporal.updatedAt()`, which always sets both phases and is
also rejected at the PSL layer via `PSL_PRESET_NOT_OPTIONAL`.
Per CLAUDE.md ("Don't design for hypothetical future requirements"),
collapse the check to "nullable + any executionDefaults = error" and
update the error message accordingly. Drop the dedicated test that
asserted the permissive branch. Re-add the allowance when a real preset
(e.g. `temporal.lastModifiedAt()` with onUpdate-only and a nullable
column) needs it, alongside that preset's own tests.
- Replace Phase B parity-note for SQLite's flat `dateTime` preset with a consolidation note pointing at the new `temporalAuthoringPresets()` helper (the flat preset was dropped; the consolidation makes per-target drift structurally impossible). - Update the "temporal.updatedAt() semantics" RD to reflect that the `nullable + onUpdate-only` allowance is no longer speculatively built in — a future onUpdate-only preset will introduce it alongside its own tests. - Add a "YAGNI cuts at PR-close" RD recording the two forward-compat hooks removed before merge: `applyOnEmptyUpdate` opt-in and `nullable + onUpdate-only` allowance.
Resolves a single modify/delete conflict on `docs/products/psl/README.md`. The file was deleted on main in commit b5c3381 ("elevate PSL authoring to a top-level May workstream") for being "significantly stale, unreferenced, and actively misleading." This branch had previously made small edits to the same file as part of Phase D (spec AC9 / FR10 named it as the canonical PSL doc). Resolution: accept main's deletion. The temporal-preset writeup survives in the package READMEs (`packages/2-sql/2-authoring/contract-psl/README.md`, `packages/2-sql/2-authoring/contract-ts/{README.md,API.md}`), none of which link back to the deleted file. A fresh canonical PSL doc is owned by the May WS5 workstream and is out of scope for this PR. `plan.md` records the AC9/FR10 adjustment. Validation: full package test suite green post-merge (sql-contract-psl, sql-contract-ts, sql-runtime, sql-orm-client) plus `pnpm lint:deps`.
…sting Per CodeRabbit review on PR #422: `resolveAuthoringColumnDefaultTemplate` in `framework-authoring.ts` was casting `value as ColumnDefaultLiteralInputValue` without runtime validation. Since `resolveAuthoringTemplateValue` returns `unknown` (it dereferences caller-provided `AuthoringArgRef` indices into arbitrary user args), the cast would silently emit class instances or non-JSON-serializable types into the contract. Add an `isColumnDefaultLiteralInputValue` predicate to `contract/types.ts` that recursively validates JSON primitives, plain arrays/objects of JSON values, and `Date` instances. Use it in `framework-authoring.ts` to throw a clear error when a resolved literal default doesn't match the input shape — mirrors the pattern already used by `resolveExecutionMutationDefaultPhase` with `isExecutionMutationDefaultValue`. Drops the cast entirely; the predicate narrows `value` to the exact type.
…dule Per CodeRabbit review on PR #422: `src/core/timestamp-now-generator.ts` mixed control-plane (`timestampNowControlDescriptor`, `temporalAuthoringPresets`) and runtime-plane (`timestampNowRuntimeGenerator`) implementations in a single file. The runtime function pulled in `RuntimeMutationDefaultGenerator` from `@prisma-next/sql-runtime`, dragging a runtime-plane import into a file otherwise consumed only by control-plane callers. Extract `timestampNowRuntimeGenerator` into a dedicated `src/core/timestamp-now-runtime-generator.ts`. The control-plane file no longer imports from `@prisma-next/sql-runtime`. `src/exports/runtime.ts` re-exports from the new location. No behavior change; `temporal.updatedAt()` and the per-target adapter wiring continue to resolve the same descriptor + generator pair.
Per CodeRabbit review on PR #422: the `stableAcrossRows` test compared `.getTime()` across the three Dates observed in a 3-row bulk insert. That assertion would still pass if the generator produced three distinct `Date` instances within the same millisecond, defeating the point of the test. Tighten to identity (`toBe`), so the test fails unless the cached `Date` instance is reused across rows — which is exactly what `stableAcrossRows` + `acrossRowsCache` claim to do.
Keep temporalAuthoringPresets generic over the target codec and native type strings so downstream contract-builder type assertions retain exact timestamp codec literals after the PR merge with main.
wmadden
left a comment
There was a problem hiding this comment.
Code Review — PR #422
- PR: feat(sql): timestamp authoring via temporal.* preset surface (Postgres + SQLite)
- Linear: TML-2379
- Branch:
feat/created-updated-at-authoring→main - Review range:
origin/main...HEAD - Canonical spec: projects/created-updated-at-authoring/spec.md
Summary
The architectural pivot itself (attribute path → field-preset registry) is sound. The two blockers are about ensuring the new surface ships in the right shape and that the spec's "structurally impossible" guarantee is actually delivered:
- F01 (Blocker) — the spec's compose-time cross-registry collision check (FR6a/AC6a) is implemented in the wrong layer. It guards the TS DSL but not the canonical composition site that PSL consumes, so PSL composition can compose ambiguous registries silently. AC6a verdict: FAIL.
- F16 (Blocker) — the new
RuntimeMutationDefaultGenerator.stableAcrossRows: booleanflag and its cache-by-columnNamekeying together encode an underspecified scope that doesn't correspond to any natural semantic claim. Should be a discriminatedstability: 'field' | 'row' | 'query', with the cache strategy derived from the declared scope. In-scope for this PR because both surfaces are new here and have no external consumers — landing the boolean and renaming later is strictly more work than landing the right shape now.
The dual-registry split that F01 and F15 are downstream of has its own dedicated artifact: design-note-unify-authoring-registries.md (already shared with the author). Collapsing the type-constructor and field-preset registries into a single registry eliminates F01, F15, and RD9's tiebreaker concern by removing the duplication they're symptoms of. The note frames this as a follow-up project — out of scope for this PR; F01 and F15 should ship their interim fixes here, and the design note tracks the durable cleanup.
Smaller findings cluster around: hardcoded namespace coupling that should be registry-derived (F15), dead descriptor fields (F04), template advertising gaps for the project's titular feature (F06), drift-prone duplicated namespace checks (F08), and AC test coverage gaps (F05). Hygiene-level concerns in F09, F10. F03 is superseded by F16.
Findings at a glance
| ID | Severity | Title |
|---|---|---|
| F01 | Blocker | Cross-registry collision check guards only TS DSL, not PSL |
| F16 | Blocker | stableAcrossRows boolean ships the wrong API shape; rename to discriminated stability |
| F15 | High | CURATED_NAMESPACES hardcodes namespace ownership; should be registry-derived |
| F04 | High | applicableCodecIds dead data on timestampNow; spec NFR3 framing wrong |
| F02 | Medium | fieldDeclaresTemporalPreset hardcodes temporal; will silently rot |
| F06 | Medium | AC8 templates only migrated createdAt; updatedAt not demonstrated |
| F08 | Medium | Two field-resolution sites duplicate the namespace check |
| F05 | Minor | Test gaps for AC5a, AC5f, AC5g, AC5i |
| F07 | Minor | Parity-test "shared comparator helper" claim doesn't match code |
| F09 | Minor | BUILTIN_FIELD_ATTRIBUTE_NAMES ↔ REMOVED_ATTRIBUTE_NAMES overlap unguarded |
| F10 | Minor | assertNoCrossRegistryCollisions early-out comment missing |
| F03 | Superseded | acrossRowsCache keying doc — superseded by F16 |
| F11–F14 | Deferred | Out of scope; see Deferred section |
Findings
Blockers
F01 — Cross-registry collision check guards only the TS DSL path; PSL composition is silently un-guarded
- Location: packages/1-framework/1-core/framework-components/src/control/control-stack.ts — lines 220–252 (
assembleAuthoringContributions); paired with packages/2-sql/2-authoring/contract-ts/src/composed-authoring-helpers.ts — lines 232–255 (assertNoCrossRegistryCollisions) - Issue: Spec FR6a/AC6a requires that "the framework rejects any path that appears in both
authoringContributions.fieldandauthoringContributions.type" at composition time. The only implementation of this check isassertNoCrossRegistryCollisionsincomposed-authoring-helpers.ts, which is invoked fromcreateComposedAuthoringHelpers— the TS DSL entry point only. The PSL composition path goescreateControlStack → assembleAuthoringContributions → prismaContract → interpretPslDocumentToSqlContract;assembleAuthoringContributionschecks for within-registry duplicates only (e.g. twofield.temporal.createdAtregistrations) and does not check cross-registry. A misconfigured pack that registerstemporal.somethingas both afieldPresetand atypeConstructorwould compose successfully under PSL and silently rely on RD9's runtime tiebreaker — the exact "structurally impossible" property the spec promises is not delivered for PSL users. The PR description's claim thatframework-components.authoring.test.ts covers cross-registry collision rejectionis incorrect — no such assertion exists in that file (or anywhere inframework-components). - Suggestion (interim, in-scope for this PR): Move the cross-registry check into
assembleAuthoringContributionsso it runs at the canonical composition site that both surfaces share. The existingassertNoCrossRegistryCollisionsincomposed-authoring-helpers.tscan stay as defensive depth, or be removed in favor of the canonical check (it's redundant once the framework function enforces it). Add aframework-components.authoring.test.tstest that constructs descriptors withfield.shared.thingandtype.shared.thingand asserts the throw. - Durable fix (separate follow-up project): See
design-note-unify-authoring-registries.md. Collapsing the dual registries into one eliminates the cross-registry collision concept entirely — there's no second registry to collide with. The interim fix here goes away when the collapse lands, which is a good outcome (fewer guards needed when the duplication is gone).
F16 — stableAcrossRows boolean ships an implementation choice into the API; rename to a discriminated stability scope (in-scope for this PR)
-
Location: packages/2-sql/5-runtime/src/sql-context.ts — lines 66–78 (
RuntimeMutationDefaultGenerator.stableAcrossRows?: boolean), lines 740–760 (resolveStableAcrossRowsValuekeyed bycolumnName); packages/2-sql/9-family/src/core/timestamp-now-generator.ts —timestampNowRuntimeGeneratoris the only generator setting the flag today; packages/3-extensions/sql-orm-client/src/collection.ts — lines 122–135 (caller wiring) -
Issue: The current
stableAcrossRows: booleanflag exposes a leaky abstraction. The boolean encodes "this generator's value is stable across some scope," but it doesn't say which scope — and the implementation made a specific choice (cache bycolumnName) that none of three natural scope semantics actually corresponds to:- Not "field" (per call) — two rows of the same column share, so it's stronger than per-call.
- Not "row" (per row) — two columns of the same row don't share, so it's weaker than row-scoped.
- Not "query" (per bulk operation) — two columns sharing a generator don't share their value, so it's weaker than query-scoped.
It's a confused middle: "stable per (column, generator) within an operation," which doesn't correspond to any natural semantic claim a generator author would want to make. The reason it exists is operational ("the cheapest cache key that worked for the timestamp case"), not conceptual. The generator author has no way to express "I want this value shared across columns too" or "I want it per row but shared across columns of that row." The boolean has only one knob; the implementation chose one of several reasonable interpretations and that choice isn't visible from the descriptor surface.
This will compound: future generators added to the framework (
requestId,batchId,correlationId-style helpers, or row-scoped sequence generators) will set the boolean without knowing what scope they're opting into, and inherit the same confused middle. The only generator using the flag today istimestampNow; the cost of fixing this rises with every new opt-in. -
Suggestion: Rename the flag to a discriminated value naming the scope, and derive the cache strategy in the framework rather than expecting the generator to know about cache keys:
type GeneratorStability = 'field' | 'row' | 'query'; interface RuntimeMutationDefaultGenerator { readonly id: string; readonly generate: (params?: Record<string, unknown>) => unknown; readonly stability: GeneratorStability; }
Semantics:
stabilityValue is constant within… Cache strategy Use case 'field'one defaulting site (one column, one row) no cache; call per defaulting site UUIDs, CUIDs, ULIDs, nanoid — one fresh value per site 'row'one row of one operation cache key (generatorId, rowIndex)A correlation id stamped into multiple columns of one row 'query'one ORM operation cache key generatorIdtimestampNow— one value across all rows and all columns of one bulk operationRecommended companion changes:
- Make the field required, not optional with a default. There aren't many generator descriptors (UUIDs, CUIDs, ULIDs, nanoid, ksuid, timestampNow); forcing each author to pick one of three documented values is good API hygiene. An optional field with default
'field'lets people stop thinking about this and ship the wrong scope. - Map
timestampNowRuntimeGeneratorfromstableAcrossRows: truetostability: 'query'. This is the honest scope for the timestamp use case (a single timestamp per bulk operation, regardless of how many timestamp-defaulted columns exist). It is technically a behavior change for a hypothetical model with two columns both defaulting throughtimestampNow— they'd now share a value instead of getting independent ones — but no real model does this today, and "shared" is the more semantically defensible answer if it ever arises. - Map all current per-call generators (
uuidv4RuntimeGenerator,cuidRuntimeGenerator, etc.) tostability: 'field'. - Rename
MutationDefaultsOptions.acrossRowsCachetodefaultValueCache(or justcache); the scope is now determined by the generator's declaredstability, not by the caller. - The framework's resolution becomes:
function cacheKey(stability: GeneratorStability, generatorId: string, rowIndex: number): string | null { switch (stability) { case 'field': return null; case 'row': return `${generatorId}:${rowIndex}`; case 'query': return generatorId; } }
Why this PR, not a follow-up: the boolean and its keying choice are part of this PR's new surface —
RuntimeMutationDefaultGenerator.stableAcrossRowsandMutationDefaultsOptions.acrossRowsCachewere both introduced here. Shipping them in the underspecified form locks the framework into the confused middle scope as the de-facto standard, and every future generator that opts in inherits the same defect. The honest API is part of the value this PR is delivering, not a separate workstream. The blast radius is also currently zero outside this PR —timestampNowis the only generator using the flag, the ORM client is the only caller passing the cache, and no external consumer has built against either surface yet. Landing the boolean and renaming it later is strictly more work than landing the discriminated value the first time.Failure modes get visibly absurd, which is the real win.
stability: 'query'onuuidv4is obviously wrong on its face in the descriptor literal — every UUID across the bulk insert collapses to one value, almost certainly violating a primary key constraint, and the descriptor reads aloud as "one value per query for UUID generation," which is self-evidently wrong. Compare to today'sstableAcrossRows: trueonuuidv4, which sounds like an optimization and only fails subtly (one UUID per column, repeated across rows). - Make the field required, not optional with a default. There aren't many generator descriptors (UUIDs, CUIDs, ULIDs, nanoid, ksuid, timestampNow); forcing each author to pick one of three documented values is good API hygiene. An optional field with default
Strongly recommended before merge
F15 — CURATED_NAMESPACES is a hardcoded list that duplicates information already in the composed registries
-
Location: packages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.ts — line 111 (
CURATED_NAMESPACES = new Set(['temporal'])), lines 139–147 (checkUncomposedNamespaceconsults it), lines 250–256 (open-coded duplicate consults it again — see F08), lines 425–436 (resolveFieldTypeDescriptorconsults it to choosePSL_UNKNOWN_FIELD_PRESETvs. type-constructor fallback) -
Issue:
CURATED_NAMESPACESintroduces a third "namespace ownership" bucket alongsidedb/familyId/targetId/composedExtensionsfor namespaces the framework hardcodes as "blessed." But thetemporal.*presets are registered by the family pack (@prisma-next/family-sql/control→temporalAuthoringPresets), and the family pack is always composed when a SQL target is selected — so the information "thetemporalnamespace is owned by something composed" is already present inauthoringContributions.field.temporal. The hardcoded list duplicates it. This couples the framework's namespace gate to specific namespace names that should live entirely in pack contributions, which is the same coupling the rest of the system carefully avoids (the framework doesn't know whichpgvector.*paths exist either — that lives in the extension pack). RD10 anticipates exposingid.*post-merge, which under the current design would mean adding'id'toCURATED_NAMESPACES— the bucket grows unboundedly with no clear principle for what belongs in it. -
Suggestion (interim, in-scope for this PR): Derive valid top-level namespaces from the composed registries. The namespace exemption becomes:
function getComposedNamespaces( authoringContributions: AuthoringContributions | undefined, composedExtensions: ReadonlySet<string>, ): ReadonlySet<string> { return new Set([ ...Object.keys(authoringContributions?.field ?? {}), ...Object.keys(authoringContributions?.type ?? {}), ...composedExtensions, ]); } // checkUncomposedNamespace then becomes: if ( namespace === 'db' || namespace === context?.familyId || namespace === context?.targetId || composedNamespaces.has(namespace) ) return undefined;
The discriminator role in
resolveFieldTypeDescriptor(curated namespace →PSL_UNKNOWN_FIELD_PRESETinstead of type-constructor fallback) becomes registry-driven the same way: "is there any field preset registered under this top-level key? If yes, a leaf miss is a typo; if no, try type constructors." Same observable behavior, no hardcoded list.This collapses
CURATED_NAMESPACESentirely. Family-pack-registered namespaces liketemporal.*(today) andid.*(per RD10) work automatically because the family pack composes them, with no framework changes required to expose them. Pairs naturally with the F01 fix (move cross-registry check intoassembleAuthoringContributions) and F08 fix (collapse the open-coded duplicate ofcheckUncomposedNamespace). -
Durable fix (separate follow-up project): See
design-note-unify-authoring-registries.md. With one unified registry, the namespace gate becomes "is this namespace inObject.keys(authoringContributions.field)?" — even simpler than the interim fix here, because theObject.keys(...field)∪Object.keys(...type)union collapses to a single lookup.
F04 — applicableCodecIds is dead data on timestampNow; spec NFR3's framing is itself wrong
-
Location: packages/2-sql/9-family/src/core/timestamp-now-generator.ts — lines 15–26 (
timestampNowControlDescriptorrequires anapplicableCodecIdsargument); packages/3-targets/6-adapters/postgres/src/core/control-mutation-defaults.ts — lines 311–314; packages/3-targets/6-adapters/sqlite/src/core/control-mutation-defaults.ts — lines 332–335; packages/1-framework/1-core/framework-components/src/shared/mutation-default-types.ts — line 76 (the descriptor type makes the field required) -
Issue:
applicableCodecIdsis consulted in exactly one place — packages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.ts line 763, insidelowerDefaultForField, the@default(...)lowering path. That's the right job for the field: when the user writes@default(uuid())on aString, the user picked the scalar and the generator name independently, so the framework needs a hand-curated compatibility list to avoid reasoning about SQL coercion rules itself.applicableCodecIdsis load-bearing for every generator that's exposed via@default(...)(the entries indefaultFunctionRegistry—uuid,cuid,ulid,nanoid, etc.).Field presets sidestep this question entirely. The codec is intrinsic to the preset's descriptor — the pack author writes both halves of the pairing in
temporalAuthoringPresets({ codecId, nativeType }), so there is no separate user choice to validate against. The "is this generator compatible with this codec?" question doesn't exist on the preset path; the preset defines the pairing.timestampNowis registered only via the preset path. It has nodefaultFunctionRegistryentry — there's no@default(timestampNow())PSL syntax — so itsapplicableCodecIdsis set by adapters and asserted by tests (postgres/test/control-mutation-defaults.test.ts:364,sqlite/test/control-mutation-defaults.test.ts:88) but never consulted by any consumer at lowering time. Pure ceremony.Spec NFR3 says: "
applicableCodecIdscontinues to exist onMutationDefaultGeneratorDescriptorbut is enforced as a registry-coherence assertion at composition time, not as a user-facing diagnostic." That framing was itself the wrong move — it tried to find a new job for the field on the preset path because it didn't notice the field becomes unnecessary there. Assertingpreset.output.codecId ∈ generator.applicableCodecIdsat compose time would be checking that the pack author typed in a self-consistent literal — a tautology that doesn't catch any failure mode the type system ortemporalAuthoringPresets's own structure doesn't already prevent. (The earlier draft of this finding inherited NFR3's framing and recommended adding such an assertion; that recommendation is rescinded.) -
Suggestion: Don't add the compose-time check NFR3 describes — it would be tautological. Instead, recognize the field is preset-path-irrelevant and clean up the dead data:
- Make
applicableCodecIdsoptional onMutationDefaultGeneratorDescriptorand document it as "required for generators reachable via@default(...)lowering; absent for preset-only generators."lowerDefaultForFieldbecomes the lone consumer and naturally gates on the field's presence (a preset-only generator that somehow ends up in thedefaultFunctionRegistrylookup would surface a clear "not applicable to@default(...)lowering" diagnostic). - Drop the
applicableCodecIdsargument fromtimestampNowControlDescriptorand the corresponding wiring in both adapters. Update the two adapter tests to assert the field is absent. - The cleanest endgame is splitting the descriptor type into
DefaultFunctionGeneratorDescriptor(carriesapplicableCodecIds, registered indefaultFunctionRegistry) andPresetGeneratorDescriptor(no codec list, referenced by preset descriptors). That's a wider refactor than this PR; the optional-field move is the minimum.
Also: update spec NFR3 to reflect the corrected role — "
applicableCodecIdscontinues to enforce codec/generator compatibility on the@default(...)lowering path. The field-preset path bypasses this check entirely because the preset'soutput.codecIdandexecutionDefaults.{onCreate,onUpdate}.idare co-registered." - Make
Recommended before merge
F02 — fieldDeclaresTemporalPreset hardcodes temporal, will silently fail to suppress the migration hint when other curated namespaces are added
-
Location: packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts — lines 90–92
-
Issue:
fieldDeclaresTemporalPresetchecksfield.typeConstructor?.path[0] === 'temporal'. RD10 explicitly anticipates additional curated namespaces (e.g.id.uuidv7()) being exposed in PSL in a follow-up. When that lands, the suppression rule for the@updatedAtmigration hint will not generalize — but this is the more interesting bug: when a new removed attribute hint is added (thegetRemovedAttributeHinttable is explicitly designed to grow), the suppression check still only inspectstemporal, not the namespace relevant to the new hint. The pattern silently rots. -
Suggestion: Rename and generalize. Either make the check namespace-driven (
CURATED_NAMESPACES.has(field.typeConstructor?.path[0] ?? '')and accept the over-suppression for now), or pair eachgetRemovedAttributeHintentry with a per-attribute predicate (e.g.{ hint: '...', suppressWhen: (field) => field.typeConstructor?.path[0] === 'temporal' }). Since the hint table is currently single-entry, the cleanest move is to inline the predicate alongside the hint.type RemovedAttributeRule = { readonly hint: string; readonly suppressWhen: (field: PslField) => boolean; }; const REMOVED_ATTRIBUTE_RULES: ReadonlyMap<string, RemovedAttributeRule> = new Map([ ['updatedAt', { hint: 'Use `temporal.updatedAt()` as a field-preset call instead.', suppressWhen: (field) => field.typeConstructor?.path[0] === 'temporal', }], ]);
F06 — AC8 templates only migrated createdAt; updatedAt was never added to demonstrate the preset surface
- Location: packages/1-framework/3-tooling/cli/src/commands/init/templates/code-templates.ts — lines 110–187; examples/prisma-next-demo/prisma/contract.ts; examples/react-router-demo/prisma/contract.ts
- Issue: Spec AC8 says "PSL/TS templates use the new preset surface for
updatedAt." The CLI starter templates and both example apps now usefield.temporal.createdAt(), but none of them actually showfield.temporal.updatedAt()ortemporal.updatedAt()— theupdatedAtfield isn't present in any of these. Result: the new authoring surface for the project's titular feature isn't demonstrated anywhere users would discover it. - Suggestion: Add an
updatedAtfield next to each existingcreatedAtincode-templates.ts(bothstarterSchemaTsPostgresandstarterSchemaTsMongohave parallels — TS usesfield.temporal.updatedAt(), PSL usestemporal.updatedAt()). Same for the two example contracts. ~6 lines of starter code total. Without this, the migration story for users porting Prisma 6's@updatedAtschemas isn't visible from any of the discovery surfaces.
F08 — Two field-resolution sites duplicate the curated-namespace check, drifting from checkUncomposedNamespace
- Location: packages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.ts — lines 129–149 (
checkUncomposedNamespace) and lines 250–256 (open-coded check insideresolvePslTypeConstructorDescriptor) - Issue:
resolvePslTypeConstructorDescriptorre-implements the namespace check inline with a long&&chain duplicating the conditions incheckUncomposedNamespace. If a future namespace is added toCURATED_NAMESPACESor thedbexemption logic changes, both sites must be updated in lockstep — the inline duplication is invisible to the helper. - Suggestion: Replace the open-coded check with
checkUncomposedNamespace(input.call.path.join('.'), input.composedExtensions, { familyId: input.familyId, targetId: input.targetId }). The single-namespace return ofcheckUncomposedNamespacealready handles the dotted-path case and returns the namespace prefix when uncomposed; the call site only needs to translate that into the appropriate diagnostic.
Hygiene / minor
F05 — Spec acceptance gaps: AC5a, AC5f, AC5g, AC5i have no targeted tests
- Location: packages/2-sql/2-authoring/contract-psl/test/interpreter.defaults.test.ts
- Issue: Several spec acceptance criteria for preset misuse have no focused test:
- AC5a (
temporal.updatedAt(123)→PSL_INVALID_ATTRIBUTE_ARGUMENT): the arg-coercion path exists but is not asserted on atemporal.*call. - AC5f (
temporal.updatedAt()[]→PSL_PRESET_NOT_LIST): the diagnostic exists atpsl-field-resolution.ts:251but no test exercises it. The plan acknowledges this is "likely a parser-level reject in practice" but a test would lock in which error fires first and prevent silent regression. - AC5g (
f DateTime @default(temporal.updatedAt())→PSL_INVALID_DEFAULT_EXPRESSIONor equivalent): no test. The path is a real user mistake worth nailing down. - AC5i (
f temporal.updatedAt() temporal.createdAt()→ parse or resolution error): no test. Spec says "verify in Phase B"; not done.
- AC5a (
- Suggestion: Add four small focused tests under
interpreter.defaults.test.tsfield-preset misusedescribe block. Each is a 4-line assertion againstresult.failure.diagnostics. The implementation does not need to change.
F07 — Parity-test description references a "shared deterministic-sort comparator helper" that doesn't exist
- Location: packages/2-sql/2-authoring/contract-psl/test/ts-psl-parity.test.ts — lines 405–487
- Issue: Both the spec (FR4, AC3) and PR description claim parity is "verified via a single shared comparator helper used by both Postgres and SQLite parity tests" / "a single shared deterministic-sort comparator helper drives the parity tests." In practice, the parity tests use plain
expect(interpreted.value).toEqual(tsContract). That works (object equality is order-insensitive on object keys), but the descriptive language overpromises. The two timestamp-parity tests are also near-duplicates; the only differences are the target pack and the codec map. - Suggestion: Either (a) actually extract the helper as promised — a small
expectContractsEquivalent(actual, expected)(and possibly arunTimestampParityTest({ targetPack, scalarTypeDescriptors, authoringContributions })table-driven harness), or (b) remove the "shared comparator helper" wording from the spec and PR description so future readers don't search for a helper that isn't there.
F09 — validateFieldAttributes evaluates getRemovedAttributeHint for every attribute, including known builtins (after the BUILTIN_FIELD_ATTRIBUTE_NAMES short-circuit)
- Location: packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts — lines 102–137
- Issue: The flow is correct (
if (BUILTIN_FIELD_ATTRIBUTE_NAMES.has(attribute.name)) continue), but the hint table is conceptually about removed attributes — yet a future entry ingetRemovedAttributeHintfor, say,'unique'would silently never fire because'unique'is inBUILTIN_FIELD_ATTRIBUTE_NAMES. This isn't a bug today, but it's a footgun: the hint table's contract isn't enforced anywhere. A small unit test or runtime assertion would help — e.g. asserting at module load time thatBUILTIN_FIELD_ATTRIBUTE_NAMES.intersection(REMOVED_ATTRIBUTE_NAMES) === empty. - Suggestion: Add a tiny module-load assertion (or a test that imports both sets and asserts no overlap). Cheap insurance for a hint-system that's explicitly designed to grow.
F10 — assertNoCrossRegistryCollisions early-out on empty typePaths short-circuits the field-only check
- Location: packages/2-sql/2-authoring/contract-ts/src/composed-authoring-helpers.ts — lines 232–255
- Issue: When
typeNamespaceis empty, the function returns immediately. That's correct (no possible collision) but means the TS DSL path silently skips the within-field-registry duplicate check — relying oncomposeFieldNamespace'smergeHelperNamespacesto have already thrown for those. That dependency is fine but undocumented; ifcomposeFieldNamespaceever stops throwing on dup, this function would not catch it. A short comment noting the dependency on the upstream merge throwing for within-registry dups would prevent confusion. - Suggestion: Add a comment above the early-out:
// Within-registry duplicate detection is handled upstream by mergeHelperNamespaces during composeFieldNamespace / composeTypeNamespace. This function only handles the cross-registry case.
F03 — acrossRowsCache keying by column name not generator id; runtime doc misleading (superseded by F16)
- Location: packages/2-sql/5-runtime/src/sql-context.ts — lines 740–760 (the cache logic) and 66–78 (the doc on
RuntimeMutationDefaultGenerator.stableAcrossRows) - Issue: The cache key is
columnName, which means a model with two columns both wired totimestampNow(e.g.createdAtandupdatedAt) gets two differentDatevalues within the same bulk operation. The doc onstableAcrossRowssays "a single ORM operation that lowers to one bulk mutation … reuses one generated value across every row that needs this default" — read literally, that would imply one timestamp shared across all columns and rows, which isn't what the implementation does. - Suggestion: Superseded by F16 — F16 proposes renaming the boolean to a discriminated
stability: 'field' | 'row' | 'query'so the scope is part of the API rather than an implementation detail of the cache key. With F16 in scope for this PR, F03's documentation tightening is moot. Kept listed only as a fallback if F16 is rejected: tighten the doc to "reuses one generated value per (column, generator) across every row in the bulk operation," and optionally rename the parameter tobulkOperationCache.
Deferred (out of scope)
F11 — PSL_INVALID_TYPE_CONSTRUCTOR_ARITY → PSL_INVALID_NAMESPACED_CALL_ARGUMENT rename
- Location: usage of
PSL_INVALID_ATTRIBUTE_ARGUMENTfor namespaced-call arg errors across psl-column-resolution.ts and field-preset arity-validation paths - Why deferred: Spec RD11 explicitly defers this rename to a follow-up; the rename would also touch genuine attribute-arg errors (
@id(badarg)) and become a wider refactor than this project's scope. Current state: field-preset arity/arg errors emit the samePSL_INVALID_ATTRIBUTE_ARGUMENTas type-constructor arity errors, accepting the historical name. Honest rename is its own ticket.
F12 — Family-level ID presets (id.uuidv7, etc.) not exposed in PSL
- Location: packages/2-sql/9-family/src/core/authoring-field-presets.ts
- Why deferred: NFR4 explicitly excludes exposing the family-level ID helpers as PSL syntax during this project. The dispatch path supports them (verified by the synthetic-preset test), but adding
idtoCURATED_NAMESPACESand shipping PSL tests/docs is its own follow-up. RD10 commits to this path post-merge.
F13 — Mongo support
- Location: out-of-scope (no Mongo code touched)
- Why deferred: Spec non-goals explicitly exclude Mongo. The contract IR change is reusable; Mongo wiring is a separate workstream.
F14 — nullable + onUpdate-only allowance for a future temporal.lastModifiedAt() preset
- Location: packages/2-sql/2-authoring/contract-ts/src/build-contract.ts (the now-tightened nullable+executionDefaults rejection)
- Why deferred: A previous draft included this hook for a hypothetical future preset; it was correctly removed before merge per "no forward-compat hooks without users" discipline. Re-add when a real
temporal.lastModifiedAt()-style preset has a real consumer with a test. Tracked as a forward-looking decision inplan.md.
Already addressed
| ID | Description | Resolved in |
|---|---|---|
| — | Tightened nullable + executionDefaults rejection at contract-build time |
2a01ae5f9 (refactor(sql,authoring): tighten nullable+executionDefaults rejection) |
| — | Dropped speculative applyOnEmptyUpdate opt-in on RuntimeMutationDefaultGenerator |
fa2c8d2e6 (refactor(sql,runtime): drop applyOnEmptyUpdate opt-in) |
| — | Centralized temporalAuthoringPresets helper across Postgres + SQLite (was duplicated) |
6ec547a95 (refactor(sql,family): share temporal.* preset registration across targets) |
| — | Migration hint suppression when temporal.* already declared |
b9a2caf18 (feat(psl)!: remove @updatedAt attribute, add migration hint) |
| — | Re-namespacing presets under field.temporal.* (was field.{createdAt,updatedAt} flat) |
f3b748df8 (feat(targets): re-namespace timestamp presets under field.temporal) |
| — | Compose-time generator validation + MISSING_MUTATION_DEFAULT_GENERATOR envelope |
89e15f591 (feat(runtime): validate mutation default generators at execution context creation) |
| — | Bulk-insert timestamp stability via stableAcrossRows + acrossRowsCache |
146242c1a (fix(orm-client): apply @updatedAt to ORM updates and stabilize across rows) |
| — | Singular executionDefault collapsed to executionDefaults: { onCreate, onUpdate } |
40462aa91 (refactor(sql): collapse executionDefault into executionDefaults) |
Acceptance-criteria verification
| AC | Verdict | Detail |
|---|---|---|
AC1 — createdAt temporal.createdAt() emits now() storage default + no execution default; equivalent @default(now()) PSL emits same |
PASS | interpreter.defaults.test.ts:283 (lowers temporal.updatedAt() to create and update execution defaults) implicitly covers createdAt via the temporal.createdAt() path; ts-psl-parity.test.ts Postgres/SQLite tests assert expect(interpreted.value).toEqual(tsContract) for the @default(now()) PSL spelling vs field.temporal.createdAt() TS spelling — proving byte-equivalence between the two surface spellings. |
AC2 — updatedAt temporal.updatedAt() emits non-null timestamp + execution default with onCreate+onUpdate referencing timestampNow |
PASS | interpreter.defaults.test.ts:283 for Postgres + :316 for SQLite both interpret the PSL and assert the storage column is non-null and the execution default carries both onCreate and onUpdate keyed to timestampNow. |
| AC3 — Equivalent SQL TS model emits same contract as PSL for Postgres + SQLite | WEAK | ts-psl-parity.test.ts proves equivalence for the cross-spelling pair (@default(now()) PSL vs field.temporal.createdAt() TS) and for temporal.updatedAt() PSL vs field.temporal.updatedAt() TS. The "spelling-for-spelling" pair (temporal.createdAt() PSL vs field.temporal.createdAt() TS) is not directly asserted; the parity tests instead use the @default(now()) spelling on the PSL side. The cross-spelling assertion is actually a stronger property than the spec asks for, but the literal AC text isn't met — and the PR's claim of "a single shared deterministic-sort comparator helper" used by both targets did not materialize as a separate utility (expect(...).toEqual(...) is used directly). |
AC4 — @updatedAt produces PSL_UNSUPPORTED_FIELD_ATTRIBUTE enhanced with hint pointing at temporal.updatedAt(); hint suppressed when field already declares any temporal.* preset; no codec-applicability messaging; BUILTIN_FIELD_ATTRIBUTE_NAMES no longer contains 'updatedAt' |
PASS | interpreter.defaults.test.ts:352, :380 test both directions (presence with literal temporal.updatedAt() substring, and suppression when the field already declares temporal.updatedAt()). psl-field-resolution.ts:63-69 confirms 'updatedAt' is no longer in the builtin set. The diagnostic message contains no codec text. |
AC5a — temporal.updatedAt(123) produces PSL_INVALID_ATTRIBUTE_ARGUMENT |
NOT VERIFIED | The arg-coercion path exists in instantiatePslFieldPreset (lines 319–347) and would emit the diagnostic, but no test asserts it on a temporal.* call. The closest covered case is validateAuthoringHelperArguments arity tests in framework-components.authoring.test.ts, which are unit-level and don't exercise the PSL code path that translates the throw into a diagnostic. |
AC5b — temporal.foo() produces PSL_UNKNOWN_FIELD_PRESET with namespace + path |
PASS | interpreter.defaults.test.ts:571 asserts the code, the source span, and the message contains 'temporal.foo'. |
AC5c — weather.updatedAt() produces PSL_EXTENSION_NAMESPACE_NOT_COMPOSED |
NOT VERIFIED | Spec acknowledges "Already worked via the existing namespace gate; no focused test added in Phase A." The path through resolvePslTypeConstructorDescriptor → reportUncomposedNamespace exists, but no test asserts the diagnostic on a non-curated namespace specifically for the post-pivot field-preset dispatch flow. Worth a regression test. |
AC5d — updatedAt temporal.updatedAt() @default(now()) produces PSL_PRESET_AND_DEFAULT_CONFLICT |
PASS | interpreter.defaults.test.ts:517 asserts the new code on the @default(...) span. |
AC5e — updatedAt temporal.updatedAt()? produces PSL_PRESET_NOT_OPTIONAL |
PASS | interpreter.defaults.test.ts:490 asserts the diagnostic on the optional case. |
AC5f — updatedAt temporal.updatedAt()[] produces PSL_PRESET_NOT_LIST |
NOT VERIFIED | The diagnostic exists at psl-field-resolution.ts:251; spec acknowledges "Likely a parser-level reject in practice" but no test exists either way. The actual error pathway (parser reject vs interpreter PSL_PRESET_NOT_LIST) is undetermined. |
AC5g — f DateTime @default(temporal.updatedAt()) produces PSL_INVALID_DEFAULT_EXPRESSION (or closest stable code) |
NOT VERIFIED | Spec acknowledges "Untested — exercises the default-function-registry path." The path is real (a user porting Prisma 6 schemas could write it) and the diagnostic surface should be locked in. |
AC5h — id temporal.updatedAt() @id produces PSL_PRESET_AND_ID_CONFLICT |
PASS | interpreter.defaults.test.ts:544 asserts the code on the @id span. |
AC5i — f temporal.updatedAt() temporal.createdAt() produces a parse-time or resolution-time error |
NOT VERIFIED | Spec acknowledges "Likely already a parse error; verify in Phase B." No test confirms either direction. |
| AC5j — superseded by AC4 hint-suppression | PASS | Explicitly superseded; covered by AC4 suppression. |
| AC6 — Generic field-preset dispatch verified via synthetic preset | PASS | interpreter.defaults.test.ts:412 registers a synthetic temporal.exampleField() preset and confirms PSL resolves it through the same path used by the real temporal.{createdAt,updatedAt} pair. The descriptor and storage default are asserted; the absence of an execution mutation default is asserted. Locks in genericness. |
| AC6a — Composition rejects collisions across registries; second test fixture confirms within-registry duplicate-name guard regression | FAIL | The cross-registry check exists only in composed-authoring-helpers.ts:232 and runs only on the TS DSL path. The PSL composition path goes through assembleAuthoringContributions (framework-components/control/control-stack.ts:220), which only checks for within-registry duplicates. A pack that registers the same path as both fieldPreset and typeConstructor will compose successfully when consumed via PSL, defeating the spec's "structurally impossible at runtime" framing. The PR description's claim that framework-components.authoring.test.ts covers cross-registry collision rejection is incorrect — no such assertion exists in that file (the file has cross-registry-related code in authoring-helper-runtime.test.ts:326 for the TS DSL only). The within-registry duplicate guard is tested in control-stack.test.ts:172 (throws on duplicate field preset paths), so the regression-guard half of AC6a passes. See F01. |
AC7 — SQLite PSL + TS authoring accepts same temporal.* model as Postgres, emits SQLite-native codecs/defaults, provider stays target-generic |
PASS | interpreter.defaults.test.ts:316 for SQLite + ts-psl-parity.test.ts:436 SQLite parity test. SQLite-specific codec (sqlite/datetime@1) and native-type (text) are asserted. |
| AC8 — Examples and templates updated to use the preset surface | WEAK | examples/prisma-next-demo/prisma/contract.ts and examples/react-router-demo/prisma/contract.ts use field.temporal.createdAt() (verified). CLI templates in code-templates.ts:164, 177 use field.temporal.createdAt() for createdAt — but no template field actually uses temporal.updatedAt() or field.temporal.updatedAt(). Spec text explicitly says "templates use the new preset surface for updatedAt" — that didn't happen. The createdAt migration is done; the updatedAt advertisement is not. See F06. |
| AC9 — Documentation reflects the preset surface in canonical location + short summaries in package READMEs | PASS | docs/products/psl/README.md:63-67 lists temporal.createdAt() / temporal.updatedAt() and the @default(now()) parallel and explains the curated-namespace exemption. packages/2-sql/2-authoring/contract-psl/README.md:18, 67-72 carries the timestamp authoring summary. packages/2-sql/2-authoring/contract-ts/README.md:19 references field.temporal.createdAt() / field.temporal.updatedAt(). All three documentation surfaces consistent. |
Acceptance-criteria summary
| Result | Count | ACs |
|---|---|---|
| PASS | 11 | AC1, AC2, AC4, AC5b, AC5d, AC5e, AC5h, AC5j, AC6, AC7, AC9 |
| FAIL | 1 | AC6a |
| NOT VERIFIED | 5 | AC5a, AC5c, AC5f, AC5g, AC5i |
| WEAK | 2 | AC3, AC8 |
What looks solid
- Centralized
timestampNow+temporal.*registration. packages/2-sql/9-family/src/core/timestamp-now-generator.ts —timestampNowControlDescriptor,timestampNowRuntimeGenerator, andtemporalAuthoringPresets({ codecId, nativeType })all live in one module. Each adapter contributes only the(codecId, nativeType)pair, eliminating descriptor drift between targets by construction. ADR 005/006/096 honored. - Generic field-preset dispatch with synthetic-namespace test. packages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.ts —
getAuthoringFieldPresetwalks any registered path, and thetemporal.exampleField()synthetic-preset test ininterpreter.defaults.test.tslocks in genericness. Good RD8 implementation. - PSL → typed-args coercion lives in PSL.
instantiatePslFieldPresetperforms argument coercion before invoking the framework's typed-input-onlyinstantiateAuthoringFieldPreset. Preserves TS's zero-runtime-validation cost. Good RD12 implementation. - Phase-aware
executionDefaultsresolution + runtime guards.instantiateAuthoringFieldPresetresolvesonCreateandonUpdateindependently and validates each viaisExecutionMutationDefaultValue. Both negative paths (non-generator value, non-string id) are tested. - Runtime startup-time generator validation.
assertMutationDefaultGeneratorsAvailablewalks the contract before any mutation can fire;RUNTIME.MISSING_MUTATION_DEFAULT_GENERATORis structured. Fail-fast at the right moment. - Bulk-insert stability opt-in shape is minimal. Generators that don't opt in retain per-call behavior; callers that don't pass a cache retain per-call behavior. Per-row generators (
uuidv4,cuid) are unaffected. The opt-in design is sound. (The flag's name and the cache keying are addressed in F16.) @updatedAtremoval is clean.BUILTIN_FIELD_ATTRIBUTE_NAMESno longer contains'updatedAt';lowerUpdatedAtAttributeand friends are deleted; the migration hint is suppressed when the field already declares anytemporal.*preset.- Plan-doc discipline. Two forward-compat hooks (
applyOnEmptyUpdateand thenullable + onUpdate-onlyallowance) were removed before merge with explicit YAGNI rationale captured in plan.md. This is the right discipline; the rationale will help future re-introducers.
Acts on findings from a fresh review pass over the wmadden DM-review fixes:
- control-stack.ts merge walker now uses the canonical
isAuthoringTypeConstructorDescriptor / isAuthoringFieldPresetDescriptor
guards (which require a non-null output) instead of weaker kind-only
locals, so the walker and assertNoCrossRegistryCollisions agree on
what counts as a leaf descriptor.
- hasRegisteredFieldNamespace promoted from psl-column-resolution.ts
to framework-authoring.ts and tightened to reject leaf-shaped roots:
a top-level field-preset descriptor (e.g. field: { Foo: { kind: ... } })
no longer counts as a namespace and will not silently exempt @Foo.bar
from the PSL extension-namespace gate.
- PSL_UNKNOWN_FIELD_PRESET now carries data: { namespace, helperPath }
via a new reportUnknownFieldPreset helper that mirrors
reportUncomposedNamespace, so machine consumers (agents, IDE
extensions) do not have to parse the prose.
- Dropped duplicate temporal.foo() unknown-preset test; the audit.foo()
variant proves the registry-derived rule generalizes beyond curated
namespaces.
- Simplified temporalAuthoringPresets as const satisfies constraint
to Record<string, AuthoringFieldPresetDescriptor>.
- Added a one-line comment at composed-authoring-helpers.ts:253 noting
the call mirrors the canonical assembleAuthoringContributions seam,
to forestall future "this is duplicated" deletions.
No behavior change for valid descriptors.
…only timestampNow Addresses GitHub review F16 (Blocker) and F04 (High) on PR #422. F16 — Replace RuntimeMutationDefaultGenerator.stableAcrossRows: boolean with the required discriminated stability: "field" | "row" | "query": - "field": one value per defaulting site (UUIDs, CUIDs, ULIDs, nanoid, ksuid, uuidv7) — no cache. - "row": one value across all defaulting sites of one row (correlation ids stamped into multiple columns of one row) — fresh per-call cache keyed by generatorId, framework-managed. - "query": one value across all rows and columns of one ORM operation (timestampNow) — caller-provided defaultValueCache keyed by generatorId. Renames MutationDefaultsOptions.acrossRowsCache to defaultValueCache; the scope is now declared by the generator, not the caller. timestampNowRuntimeGenerator declares stability: "query"; all builtin id generators (uuidv4, cuid, cuid2, nanoid, ulid, ksuid, uuidv7) declare stability: "field". The dishonest "(generatorId, columnName)" keying is gone — the row case is now expressible without a leaky abstraction, and the timestampNow case becomes "one value per query" verbatim instead of accidental. F04 — Make MutationDefaultGeneratorDescriptor.applicableCodecIds optional, and drop it from timestampNowControlDescriptor: - The field is preset-path-irrelevant: a preset descriptor co-registers the codec, so there is no separate user choice to validate against. Documented as required only for generators reachable via @default(...) lowering (entries in defaultFunctionRegistry). - timestampNowControlDescriptor() now takes no arguments; postgres and sqlite adapter wiring drop the codec id list (PG_TIMESTAMP_CODEC_ID, PG_TIMESTAMPTZ_CODEC_ID, SQLITE_DATETIME_CODEC_ID no longer imported in the postgres file; sqlite still uses SQLITE_DATETIME_CODEC_ID for scalar type descriptors). - lowerDefaultForField gains a clear "not applicable to @default(...) lowering" diagnostic when a preset-only generator surfaces on the default-function path, with a hint pointing at the corresponding preset surface (e.g. temporal.updatedAt()). Both changes touch surfaces introduced in this PR; no external consumers. BREAKING: stability is required on RuntimeMutationDefaultGenerator; external generator authors must pick "field", "row", or "query".
…ck, demo updatedAt Addresses GitHub review F02, F06, F08 (Medium) on PR #422. F02 — Removed-attribute hints now carry their own suppression predicate. Replaces the hardcoded `fieldDeclaresTemporalPreset` check (which only recognized the `temporal.*` namespace) with a per-rule `REMOVED_ATTRIBUTE_RULES` map that pairs each migration hint with its own `suppressWhen` predicate. A future entry for, say, `@id` ↔ `id.uuidv7()` cannot silently inherit the wrong suppression — each rule is self-contained. F08 — Drop the open-coded namespace check inside `resolvePslTypeConstructorDescriptor` and reuse the existing `checkUncomposedNamespace` helper. The two sites no longer drift if the recognized-namespace rules change (db, family, target, registered field-preset namespaces, composed extensions). F06 — Demonstrate `temporal.updatedAt()` next to the existing `temporal.createdAt()` in: - CLI postgres PSL starter (`temporal.updatedAt()`) - CLI postgres TS starter (`field.temporal.updatedAt()`) - examples/prisma-next-demo/prisma/contract.ts (User + Post) - examples/react-router-demo/prisma/contract.ts (User + Post) - Snapshot updates for the affected starter templates Mongo templates unchanged (Mongo target is out of scope for temporal presets per spec). The `.prisma` example schemas intentionally keep `@default(now())` for `createdAt` per PR description; only TS-side contracts and CLI templates pick up the new preset surface.
Addresses GitHub review F05, F07, F09, F10 (Hygiene/Minor) on PR #422. F05 — Add four focused tests in interpreter.defaults.test.ts under the field-preset misuse describe block, locking in which diagnostic fires: - AC5a: temporal.exampleField(123) → PSL_INVALID_ATTRIBUTE_ARGUMENT (zero-arg preset called with an extra positional argument) - AC5f: temporal.exampleField()[] → PSL_PRESET_NOT_LIST - AC5g: @default(temporal.updatedAt()) → PSL_INVALID_DEFAULT_VALUE (parser-level rejection of dotted names in @default(...) — locks in the honest "this is not a valid @default(...) value" path rather than the speculative "this generator is not applicable" path) - AC5i: two consecutive type-constructor calls on the same field — parser-level reject (locks in the failure mode against future parser refactors that might silently accept the ambiguous form) F07 — Extract the shared parity harness as the spec promised. Both SQLite and Postgres timestamp parity tests now drive through one expectTimestampParity helper in ts-psl-parity.test.ts; the shared PSL schema lives at module scope. The spec/plan wording is corrected: the actual mechanism is deep structural equality (toEqual), not "deterministic-sort comparator" — the latter overpromised what the code does. F09 — Module-load assertion that BUILTIN_FIELD_ATTRIBUTE_NAMES and REMOVED_ATTRIBUTE_RULES.keys() do not intersect. The hint table is explicitly designed to grow; a future entry whose name is also a builtin would silently never fire because the validator short-circuits on builtins first. Cheap insurance. F10 — Comment the early-out in assertNoCrossRegistryCollisions explaining that within-registry duplicate detection is handled upstream by the merge walker. Forestalls "this short-circuit looks like it skips checks" reads.
The project is fully delivered; per plan.md task #133, strip the transient `projects/created-updated-at-authoring/` directory and the lone in-test reference to spec.md. The PR description, commit history, and the contract-psl tests themselves are now the canonical record of what shipped.
…ndling
Three follow-ups from the post-fix code review:
1. Promote `mergeAuthoringNamespaces` (was the byte-twin
`mergeHelperNamespaces` in composed-authoring-helpers.ts and the
local merge function in control-stack.ts) into the shared
framework-authoring module. Both surfaces now import the canonical
walker; one error message ("Helper names must be unique across
composed packs") replaces the two near-identical variants.
2. Harden the merge walker against recursion into non-object values.
When neither side of a merge is a recognized leaf descriptor AND
either side is not a plain object (e.g. a malformed
`{ kind: "fieldPreset" }` whose missing `output` causes the
canonical guard to reject it as a leaf), the walker now raises a
path-aware "malformed value" error instead of recursing into the
primitive `kind` string and infinite-looping.
Includes a regression test exercising the malformed-descriptor case.
3. Add the AC5c regression test (`weather.updatedAt()` →
`PSL_EXTENSION_NAMESPACE_NOT_COMPOSED`). Locks in the diagnostic
path through the new field-preset surface; the spec previously
said "verify in Phase B" — now it has a focused test.
No behavior change for valid inputs.
wmadden
left a comment
There was a problem hiding this comment.
Re-review — all findings resolved at 5d94ff9ec
Thanks for the very thorough turnaround. All 12 actionable findings from the first-pass review (2 blockers, 2 strongly-recommended, 3 medium, 4 hygiene/minor, 1 superseded) are addressed, with implementations that match the proposed shape. Bonus improvements (commit 5d94ff9ec) go beyond what the review called out — unified merge walker across both surfaces, malformed-value hardening on the walker (with regression test), and an AC5c regression test.
Per-finding resolution
| ID | Severity | Status | Resolved in |
|---|---|---|---|
| F01 | Blocker | ✅ Resolved | 65ef6908d fix: reject cross-registry authoring collisions — moved into assembleAuthoringContributions so both PSL and TS DSL surfaces are guarded; control-stack.test.ts:222 asserts the throw |
| F16 | Blocker | ✅ Resolved | 02fa64f98 refactor(sql,runtime)!: discriminated generator stability and preset-only timestampNow — stability: 'field' | 'row' | 'query' (required), framework-derived cache strategy via scopedCache(stability, rowCache, queryCache), acrossRowsCache → defaultValueCache rename, caches keyed by generatorId only |
| F15 | High | ✅ Resolved | 65fde4bcf fix: derive PSL preset namespaces from registry (+ 427350c62) — CURATED_NAMESPACES removed; replaced with hasRegisteredFieldNamespace(authoringContributions, ns) at both sites |
| F04 | High | ✅ Resolved | 02fa64f98 — applicableCodecIds made optional; dropped from timestampNow (descriptor now zero-arg); adapter wiring updated; bonus diagnostic in lowerDefaultForField for preset-only generators surfacing on the @default(...) path; adapter tests assert absence |
| F02 | Medium | ✅ Resolved | 9d0c7f2a8 — REMOVED_ATTRIBUTE_RULES map with per-rule suppressWhen predicate (matches the snippet recommended in the review) |
| F06 | Medium | ✅ Resolved | 9d0c7f2a8 — temporal.updatedAt() added to CLI postgres PSL/TS starters and both example contracts (User + Post) |
| F08 | Medium | ✅ Resolved | 9d0c7f2a8 — open-coded namespace check in resolvePslTypeConstructorDescriptor deleted; reuses checkUncomposedNamespace |
| F05 | Minor | ✅ Resolved | b070cb18e — AC5a, AC5f, AC5g, AC5i tests added (5d94ff9ec adds AC5c too) |
| F07 | Minor | ✅ Resolved | b070cb18e — extracted expectTimestampParity helper; spec wording corrected (was overpromising "deterministic-sort comparator") |
| F09 | Minor | ✅ Resolved | b070cb18e — module-load assertion that BUILTIN_FIELD_ATTRIBUTE_NAMES ∩ REMOVED_ATTRIBUTE_RULES.keys() = ∅ |
| F10 | Minor | ✅ Resolved | b070cb18e — comment added explaining the early-out's dependency on the upstream merge walker |
| F03 | Superseded | ✅ Resolved | Moot via F16 — (generatorId, columnName) keying is gone |
| F11–F14 | Deferred | — | Out of scope; status unchanged |
A few highlights worth calling out
F16 (stability rename). The implementation is exactly the shape proposed in the review:
stability: 'field' | 'row' | 'query'is required onRuntimeMutationDefaultGenerator(no default — every generator author has to pick one of three documented values).- The doc comment on
GeneratorStabilitycovers the per-value semantics in plain prose, with example use cases for each scope. Generator authors no longer need to know about cache keys at all. 'row'is implemented with a framework-managed per-call cache so the previously-impossible "value shared across columns of one row" case is now expressible without a leaky abstraction.timestampNowRuntimeGenerator: stability: 'query'is the honest scope for the timestamp use case (one timestamp per bulk operation, regardless of how many timestamp-defaulted columns exist).- All current id generators (
uuidv4,cuid,cuid2,nanoid,ulid,ksuid,uuidv7) declarestability: 'field'— and crucially, the descriptor reads aloud as "one value per defaulting site," which is unambiguous and won't silently rot. - Marked
BREAKING:in the commit message, surfaced in the PR description.
F04 bonus diagnostic. Beyond making applicableCodecIds optional and dropping it from timestampNow, lowerDefaultForField now emits a clear PSL_INVALID_DEFAULT_APPLICABILITY diagnostic when a preset-only generator surfaces on the @default(...) lowering path, with a hint pointing at the corresponding preset surface (e.g. temporal.updatedAt()). Defensive depth in the right spot.
F15 bonus. Beyond removing CURATED_NAMESPACES, the same hasRegisteredFieldNamespace helper drives both the namespace gate (checkUncomposedNamespace) and the discriminator role (resolveFieldTypeDescriptor) — pairs naturally with the F08 fix to collapse the duplicate site.
Bonus commit 5d94ff9ec. Three additional moves the review didn't call out:
- Promotes
mergeAuthoringNamespaces(wasmergeHelperNamespacesand a local merge function) into the shared framework-authoring module — single canonical merge walker, single error message ("Helper names must be unique across composed packs"). - Hardens the merge walker against recursion into non-object values: a malformed
{ kind: 'fieldPreset' }whose missingoutputcauses the canonical guard to reject it as a leaf no longer infinite-loops the walker; raises a path-aware "malformed value" error instead. Includes a regression test. - Adds the AC5c regression test (
weather.updatedAt()→PSL_EXTENSION_NAMESPACE_NOT_COMPOSED), closing one of the "NOT VERIFIED" rows in the original AC table.
AC table now (effectively) all PASS
The original review's AC table had 1 FAIL (AC6a), 5 NOT VERIFIED (AC5a, AC5c, AC5f, AC5g, AC5i), and 2 WEAK (AC3, AC8). The current state:
- AC6a → PASS (F01 fix)
- AC5a, AC5c, AC5f, AC5g, AC5i → PASS (F05 +
5d94ff9ec) - AC3 → PASS (F07 helper extraction)
- AC8 → PASS (F06 templates updated)
Modulo the explicit deferrals (F11–F14), every AC is covered.
Open follow-ups
The dual-registry collapse (collapse authoringContributions.type into authoringContributions.field) remains a worthwhile follow-up project — F01 and F15's interim fixes go away when it lands. Tracked in the design note already shared out-of-band; not a gating concern for this PR.
Excellent work; merging this is the right move. Tests pass on all affected packages locally.
wmadden
left a comment
There was a problem hiding this comment.
Follow-up: one new blocker identified during re-review
After posting the re-review confirming all twelve first-pass findings as resolved, one additional blocker surfaced — a layering leak that's pre-existing in this PR (introduced in commit 40d67af63) and missed in the first-pass review. Flagging now since it's the same shape of concern as the (now-resolved) CURATED_NAMESPACES issue (F15) and worth fixing in this PR while the surrounding code is fresh.
F17 — TIMESTAMP_NOW_GENERATOR_ID is a SQL-family constant living in the domain-agnostic framework layer (Blocker)
Locations:
- Definition:
packages/1-framework/1-core/framework-components/src/shared/mutation-default-types.ts:14 - Re-export:
packages/1-framework/1-core/framework-components/src/exports/control.ts:109 - Consumer importing back from framework:
packages/2-sql/9-family/src/core/timestamp-now-runtime-generator.ts:1
Issue:
TIMESTAMP_NOW_GENERATOR_ID = 'timestampNow' is defined in @prisma-next/framework-components — the target-/domain-agnostic core layer per the Architecture Overview. Three signals confirm this is misplaced:
- It's the only concrete generator id in the entire framework-components package. Every other id in the codebase (
cuid,uuidv4,nanoid,ulid,ksuid,cuid2,uuidv7) lives where its generator lives —packages/1-framework/2-authoring/ids/src/index.ts, the ID extension pack at the authoring layer. Singling outtimestampNowto live two layers higher isn't a principle, it's an accident of how commit40d67af63's "centralize timestampNow descriptor and runtime wiring" landed. - The framework never reads the constant. It defines it, re-exports it via
exports/control.ts, and never references it internally. When a layer defines a value but never uses it, the value belongs downstream. - The only consumers are siblings inside
@prisma-next/family-sql(timestamp-now-generator.ts,timestamp-now-runtime-generator.ts), and they're forced to import their own generator's id from a layer above them that has no business knowing it exists. The constant takes a round trip out and back.
This is the same shape of leak that CURATED_NAMESPACES had before F15 — a higher layer carrying domain-specific knowledge ("timestamps exist," "the temporal namespace exists") that the lower-layer owner should keep inside its own boundary. Letting it stand makes the framework's domain-agnostic claim weaker than it reads, and sets the precedent that "the framework is the right place for cross-cutting deduplication" — which would, taken to its conclusion, pull every generator id and every preset name into framework-components over time.
The 40d67af63 commit motivation read:
064: export
TIMESTAMP_NOW_GENERATOR_IDconstant andExecutionMutationDefaultPhasestype from canonical sources; replace duplicated literals/aliases across PSL/TS authoring and adapters.
This conflated two different things — type definitions (interface RuntimeMutationDefaultGenerator { id: string; ... }, legitimately framework-domain because the framework needs to know the shape of a generator descriptor) with concrete instances (a particular generator id string, owned by whoever defines the actual generator). The framework needs the type; it doesn't need the value.
Suggestion:
Move the constant to where its owner lives:
- Add
export const TIMESTAMP_NOW_GENERATOR_ID = 'timestampNow' as const;to a new file underpackages/2-sql/9-family/src/core/(e.g.timestamp-now-generator-id.ts) or directly insidetimestamp-now-generator.ts. - Drop the definition from
framework-components/src/shared/mutation-default-types.ts:14and the re-export fromframework-components/src/exports/control.ts:109. - Update the import in
timestamp-now-runtime-generator.ts:1to consume from the local sibling instead of@prisma-next/framework-components/control. - Run
pnpm lint:depsto confirm the layering is now clean for this constant.
Related (smaller) leak in the same file, worth fixing in the same change:
The docstring on MutationDefaultGeneratorDescriptor.applicableCodecIds (lines 76–84) describes itself in terms of "the @default(...) lowering path" and defaultFunctionRegistry — both PSL-authoring concepts. Framework-domain types describing themselves in terms of a downstream authoring surface is a milder version of the same leak. Either rephrase in framework-neutral terms (e.g. "registry-coherence between codec and generator on the user-chosen-scalar default path") or push the docstring down to where the consumer (lowerDefaultForField) lives.
wmadden
left a comment
There was a problem hiding this comment.
Pre-emptive approval
Approving on the explicit assumption that F17 lands as described in the previous review:
- Move
TIMESTAMP_NOW_GENERATOR_IDintopackages/2-sql/9-family/src/core/(alongsidetimestampNowControlDescriptor/timestampNowRuntimeGenerator). - Drop the definition from
framework-components/src/shared/mutation-default-types.ts:14and the re-export fromframework-components/src/exports/control.ts:109. - Update the import in
timestamp-now-runtime-generator.ts:1to consume from the local sibling. - Bundle the smaller
MutationDefaultGeneratorDescriptor.applicableCodecIdsdocstring leak in the same file (rephrase in framework-neutral terms or push the doc down to the consumer). pnpm lint:depsshould be happy.
Once that lands, no re-review needed from me — merge at will.
Everything else in this PR (all twelve first-pass findings, plus the bonus hardening from 5d94ff9ec) is solid as-is. Excellent work overall.
Addresses F17 from wmadden review: #422 (review) Move the timestamp generator id from `framework-components` (the target-/domain-agnostic core layer) to `family-sql/core/timestamp-now-generator.ts` where the generator actually lives. Three signals motivated the move: 1. It was the only concrete generator id in framework-components — every other id (`cuid`, `uuidv4`, `nanoid`, `ulid`, `ksuid`, `cuid2`, `uuidv7`) lives with its generator in `@prisma-next/ids`. 2. The framework defined the constant and re-exported it via `exports/control.ts`, but never read it internally — a value defined but never used belongs downstream. 3. The only consumers were siblings inside `family-sql/core` (`timestamp-now-generator.ts`, `timestamp-now-runtime-generator.ts`), which were forced to import their own generator id via a layer above them — a pointless round trip. Same shape of leak as the (now-resolved) `CURATED_NAMESPACES` issue from F15: a higher layer carrying domain-specific knowledge that the lower-layer owner should keep inside its own boundary. Changes: - Add `export const TIMESTAMP_NOW_GENERATOR_ID = "timestampNow" as const` to `packages/2-sql/9-family/src/core/timestamp-now-generator.ts` (alongside `timestampNowControlDescriptor` and `temporalAuthoringPresets` — its only owners). - Drop the constant from `framework-components/src/shared/mutation-default-types.ts`. - Drop the re-export from `framework-components/src/exports/control.ts`. - Update `timestamp-now-runtime-generator.ts` to import from the local sibling instead of `@prisma-next/framework-components/control`. Bundled: rephrase the `MutationDefaultGeneratorDescriptor.applicableCodecIds` docstring in framework-neutral terms. The previous wording named `@default(...)` and `defaultFunctionRegistry` — both downstream PSL-authoring concepts. The new wording describes the slot in terms of registry-coherence between independently-chosen codec and generator, which holds at the framework layer regardless of the caller. `pnpm lint:deps` clean (725 modules, 1427 deps); typecheck and tests pass for framework-components, family-sql, sql-runtime, sql-contract-psl, adapter-postgres, and adapter-sqlite. BREAKING (internal only): `TIMESTAMP_NOW_GENERATOR_ID` is no longer exported from `@prisma-next/framework-components/control`. No external consumer imported it; both internal consumers were updated.
Linear: [TML-2380 — sql: add support for id-less models](https://linear.app/prisma-company/issue/TML-2380/sql-add-support-for-id-less-models) Stacked on #422. ## Intent Make SQL PSL authoring round-trip database tables that do not have primary keys, while also lowering model-level composite `@@id` declarations into SQL storage primary keys. This keeps introspected SQL PSL emit-able without changing document-family behavior or adding runtime ORM APIs for id-less models. The PR also closes five pre-existing silent-failure paths in the identity / constraint validation surface that the multi-agent review surfaced; see "Identity & constraint validation tightening" below. ## Change map - **Implementation**: - [packages/2-sql/2-authoring/contract-psl/src/interpreter.ts](packages/2-sql/2-authoring/contract-psl/src/interpreter.ts) — `@@id` lowering, id-less acceptance, composite identity validation, and the inline-vs-block / duplicate-`@@id` conflict policy - [packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts](packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts) — reject inline `@id` on optional fields - [packages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts](packages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts) — unified `entityLabel` parameter and `findDuplicateFieldName` helper - [packages/2-sql/3-tooling/emitter/src/index.ts](packages/2-sql/3-tooling/emitter/src/index.ts) — drop the unconditional missing-primary-key throw - **Tests (evidence)**: - [packages/2-sql/2-authoring/contract-psl/test/interpreter.test.ts](packages/2-sql/2-authoring/contract-psl/test/interpreter.test.ts) — id-less, composite, mapped-composite happy paths, plus a round-trip companion that consumes the printer's snapshot output verbatim - [packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts](packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts) — 12 new diagnostic tests covering every reachable failure of the identity & constraint surface - [packages/2-sql/3-tooling/emitter/test/emitter-hook.structure.test.ts](packages/2-sql/3-tooling/emitter/test/emitter-hook.structure.test.ts) — emitter accepts model-backed tables without `primaryKey` - **Docs**: - [docs/architecture docs/subsystems/3. Query Lanes.md](docs/architecture%20docs/subsystems/3.%20Query%20Lanes.md) — record the implicit ORM single-PK invariant - **Plan/spec**: - [projects/id-less-sql-models/spec.md](projects/id-less-sql-models/spec.md) - [projects/id-less-sql-models/plan.md](projects/id-less-sql-models/plan.md) ## The story 1. The SQL PSL interpreter now treats "no identity declaration" as a valid SQL table shape and omits the storage `primaryKey` property instead of reporting `PSL_MISSING_PRIMARY_KEY`. 2. Model-level `@@id` is parsed with the existing model-attribute helpers, maps field names through `@map`, preserves the optional `map` constraint name, and feeds the same SQL primary-key node used by inline `@id`. 3. SQL emission structure validation now accepts model-backed tables without `primaryKey` while retaining validation for primary-key column references when a primary key is present. 4. Identity & constraint validation is tightened so that five pre-existing silent-failure paths (multiple `@@id` blocks, duplicate columns in `@@id`/`@@unique`/`@@index`, nullable `@id`/`@@id` columns, multi-field inline `@id`) now produce explicit diagnostics rather than emit semantically broken contracts. ## Identity & constraint validation tightening In addition to enabling id-less models, the PR adds explicit `PSL_INVALID_ATTRIBUTE_ARGUMENT` diagnostics for five pre-existing gaps where the interpreter previously accepted invalid input and emitted a structurally or semantically broken contract: - **Multiple `@@id` blocks** on the same model: previously the second silently overwrote the first; now the duplicate is rejected. - **Duplicate columns in `@@id`, `@@unique`, or `@@index`** (e.g. `@@id([email, email])`): previously emitted `columns: ['email', 'email']` — invalid SQL that fails at DDL time for `@@id`/`@@unique` and produces a wasteful no-op index for `@@index`. Now rejected at authoring time via the shared `findDuplicateFieldName` helper. - **Nullable fields used as `@id` or in `@@id`**: previously accepted, producing a NULLABLE primary-key column that the database would reject at DDL time; now rejected at authoring time with an explanatory diagnostic. - **Inline `@id` on multiple fields** (e.g. `id1 Int @id` together with `id2 Int @id`): previously silently lowered into a composite primary key whose `name` was dropped; now rejected with a hint to use `@@id([...])` instead. The conflict between inline `@id` and `@@id` on the same model also gains a single-clause diagnostic in the established voice ("cannot declare both field-level @id and model-level @@id"). ## Behavior changes & evidence - **Id-less SQL models emit successfully**: a model with no `@id` or `@@id` produces a table with no `primaryKey` while preserving columns, uniques, and model field mappings. - **Composite `@@id` lowers to SQL primary keys**: `@@id([email, token])` emits `primaryKey.columns` in field order, and mapped fields plus `map: "..."` are reflected in the contract. - **Emitter validation matches the optional storage shape**: contracts whose model table intentionally omits `primaryKey` are valid, but existing validation still checks `primaryKey.columns` when present. - **Round-trip: printer output → interpreter** is locked by a split-snapshot test pair. The 9-family side already snapshot-tests `printPsl(sqlSchemaIrToPslAst(ir))` for id-less and composite-PK tables; a new `describe('round-trips printer output', ...)` block in `interpreter.test.ts` parses those exact snapshot strings, so a drift on either side breaks one of the two suites. ## Compatibility / migration / risk - **Existing valid `@id` models continue to emit the same SQL primary-key shape** — no change to `storageHash` or `profileHash` for any pre-existing valid schema (verified per ADR 010 canonicalization rules: `id` is still emitted via `ifDefined('id', primaryKey)`, so absent values remain absent). - **The id-less acceptance is a validation relaxation**, aligning the PSL interpreter with the already-tolerant core contract type (`storage.tables.<t>.primaryKey` was already optional per ADR 172). - **The five tightenings are user-visible changes** for schemas that were previously accepted but produced semantically broken contracts. Any schema relying on the silent-failure behavior was already producing a malformed contract — these changes reject those schemas at authoring time with actionable diagnostics. No schema that produced a valid contract before is rejected now. - **`PSL_MISSING_PRIMARY_KEY` is removed** from the diagnostic set. It has no production references outside the test that was updated; this is a `ContractSourceDiagnostic` code (authoring time), not a `RuntimeError` envelope code, so ADR 027 stability rules do not apply. - **Downstream lanes are unaffected**: ORM, sql-builder, kysely-lane, relational-core, and sql-lane have zero references to `model.id` or `table.primaryKey`. The 9-family migrations / schema-verify / control-instance code paths that do reference `table.primaryKey` already optional-chain. `pnpm lint:deps` reports zero violations. - **ORM single-PK invariant** (non-goal: changing ORM ops that assume a PK fallback) is now documented in `docs/architecture docs/subsystems/3. Query Lanes.md` as an implicit invariant pending a future per-model capability gate (e.g. `sql.ormRequiresPrimaryKey`). Today the ORM lane has no code that depends on `model.id`, so id-less models remain compatible with composition; the doc records the constraint for future ORM-op authors. ## Validation - `pnpm --filter @prisma-next/sql-contract-psl test` — 132 tests pass (was 118; +14) - `pnpm --filter @prisma-next/sql-contract-emitter test` — 103 tests pass - `pnpm --filter @prisma-next/sql-contract-psl typecheck` - `pnpm --filter @prisma-next/sql-contract-emitter typecheck` - `pnpm test:packages` — 110 tasks, all green - `pnpm lint:deps` — 0 dependency violations ## Follow-ups / open questions - Per-model `sql.ormRequiresPrimaryKey` capability flag and ORM-lane composition gate (currently doc-only). - Delete `projects/id-less-sql-models/` during project close-out per `projects/README.md`. ## Non-goals / intentionally out of scope - Changing ORM operations that assume a single primary key fallback. - Adding Prisma Client-like APIs for id-less models. - Changing document or MongoDB PSL behavior. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Clarified primary-key requirements for ORM operations and guidance for id-less models. * **Bug Fixes** * Stricter validation and clearer diagnostics for primary-key/@id/@@id conflicts, duplicates, and invalid usages. * Validation now accepts tables without a primary key where appropriate. * **Tests** * Expanded coverage for primary-key scenarios, composite ids, and nullable-field round-trips. * **Tooling** * Emit now notifies the dev server about updated artifact files to improve live updates. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: jkomyno <[email protected]>
closes TML-2379
Intent
Add Prisma-compatible SQL timestamp authoring to Prisma Next via a field-preset registry path in PSL that mirrors the existing TypeScript preset path. Both surfaces consume the same registry entry, so byte-equivalence is preserved by construction.
temporal.createdAt()lowers to the same storage column default as@default(now()), so the database owns the create-time value.temporal.updatedAt()lowers tocontract.execution.mutations.defaultswith bothonCreateandonUpdateset to the target-providedtimestampNowgenerator — Prisma Next fills the timestamp on insert and on non-empty update payloads when the caller does not provide an explicit value.@default(now())continues to work as the Prisma-6-shaped alternative totemporal.createdAt().What it adds
getAuthoringFieldPresetwalker symmetric with the existinggetAuthoringTypeConstructor. Field-preset resolution runs first; type-constructor resolution is the fallback on miss. Backed by a compose-time collision check that rejects any path registered in bothauthoringContributions.fieldandauthoringContributions.type, so runtime collisions are structurally impossible.temporalnamespace exemption. Added to PSL's namespace gate alongsidedb/familyId/targetId. Markstemporalas a curated SQL-family-shared namespace and chosen for forward-compatibility with the JS/TS Temporal API.temporal.createdAt()andtemporal.updatedAt()as field-type expressions onmodelfield declarations for Postgres and SQLite.field.temporal.createdAt()andfield.temporal.updatedAt()from the same registry entries the PSL surface consumes — both surfaces share the leaf names (createdAt,updatedAt) so a single shared deterministic-sort comparator helper drives the parity tests.temporal.createdAt/temporal.updatedAtattarget.authoring.field.temporal.{createdAt,updatedAt}via a single shared helpertemporalAuthoringPresets({ codecId, nativeType })exported from@prisma-next/family-sql/control. Each target supplies only itscodecId/nativeTypepair (pg/timestamptz@1/sqlite/datetime@1); the rest of the descriptor is owned by the helper, making byte-equivalence between targets structural. ThetimestampNowgenerator descriptor + runtime generator live in the samefamily-sql/core/timestamp-now-generator.tsmodule and are wired into both adapters.PSL_PRESET_NOT_OPTIONAL), list preset (PSL_PRESET_NOT_LIST), preset +@default(...)(PSL_PRESET_AND_DEFAULT_CONFLICT— distinct fromPSL_INVALID_DEFAULT_APPLICABILITY), preset +@idwhen the preset doesn't contribute id (PSL_PRESET_AND_ID_CONFLICT), unknown preset name in a curated namespace (PSL_UNKNOWN_FIELD_PRESET). Wrong arity / wrong-typed args reuse the existingPSL_INVALID_ATTRIBUTE_ARGUMENT(RD11 — honest rename toPSL_INVALID_NAMESPACED_CALL_ARGUMENTdeferred to a follow-up).applyMutationDefaultsfills omittedupdatedAton create and on non-empty update mutations; explicit user values still win; empty update payloads skiponUpdatedefaults unconditionally (RD2). Unchanged across the pivot.Collection). Every update path —update,updateAll,updateCount, the upsert update branch, and the nested update branch inupdateFirstGraph— callsapplyMutationDefaults({ op: 'update', … }). Bulk inserts viacreateAllreuse onetimestampNowvalue across every row via a per-operationacrossRowsCache; thetimestampNowruntime generator declaresstableAcrossRows: true. Per-row generators (cuid,uuidv4, …) are unaffected.createExecutionContextwalkscontract.execution.mutations.defaultsand surfacesRUNTIME.MISSING_MUTATION_DEFAULT_GENERATORif the stack does not provide a referenced generator id.instantiateAuthoringFieldPresetreturns preciseColumnDefault/ExecutionMutationDefaultPhasestypes backed by runtime guards (isColumnDefault,isExecutionMutationDefaultValueexported from@prisma-next/contract/types);buildFieldPresetno longer needsascasts.Architecture choices
temporal.updatedAt()lowers to the existingExecutionMutationDefaultshape — bothonCreateandonUpdatewere already in the contract IR. No new contract concept introduced.executionDefaults: { onCreate?, onUpdate? }. The earlier transitionalexecutionDefaultslot was collapsed; existing generated id helpers (uuidv4,nanoid,cuid2,ulid,ksuid,uuidv7) now produce{ onCreate: ... }rather than the singular form.timestampNowlives infamily-sql+ adapters, not in@prisma-next/ids.MutationDefaultGeneratorDescriptor.buildPhasesis the single source of truth for the phases value, so PSL and TS authoring are byte-equivalent by construction.TIMESTAMP_NOW_GENERATOR_IDandExecutionMutationDefaultPhasesexported from one place each.getAuthoringFieldPresetwalks any registered field-preset path — not hardcoded totemporal.*. AC6 explicitly tests genericness via a synthetictemporal.exampleField()test fixture so the path doesn't decay into atemporal-specific shortcut.instantiatePslFieldPresetcoerces AST nodes to the descriptor's typed shape before invokinginstantiateAuthoringFieldPreset. The framework function stays typed-input-only — TS keeps its zero-runtime-validation cost.RuntimeMutationDefaultGenerator.stableAcrossRows: trueplus the caller-threadedMutationDefaultsOptions.acrossRowsCache(aMapper ORM mutation operation) is the entire mechanism. Per-row generators are unaffected.temporal.updatedAt()semantics: "last modified time", not "last update time". The preset registers bothonCreateandonUpdatetotimestampNowand the column is non-null. On insert,updatedAtequalscreatedAt; on update, it advances. PSL rejectstemporal.updatedAt()?withPSL_PRESET_NOT_OPTIONAL; TS rejects nullable + anyexecutionDefaultsat contract-build time. The choice mirrors Prisma 6 / Rails / Django conventions and preserves theupdatedAt >= createdAtinvariant soORDER BY updated_at DESCworks for fresh records too. The alternative semantic ("nullable, NULL until first update") was considered and rejected for this preset; the contract IR + runtime can support it if a future preset (e.g.temporal.lastModifiedAt()withonUpdate-only and a nullable column) is added — but the correspondingnullable + onUpdate-onlyallowance is not speculatively built in here. That PR will introduce it alongside a real production user.applyOnEmptyUpdateopt-in onRuntimeMutationDefaultGenerator(only ever exercised by a self-test; empty-update skip is now unconditional), and (2) thenullable + onUpdate-onlyallowance inbuild-contract.ts(dead code w.r.t.temporal.updatedAt()). Re-add when a real generator/preset needs them, with a test exercising real production code.ORM behavior matched against Prisma 6
@updatedAtA direct comparison with Prisma 6 (Dub port) — captured in
prisma-next-updatedat-expectations.md— surfaced two compatibility gaps that the original draft did not exercise. Both are fixed in this PR:updatedAt. Previously the runtime correctly handledapplyMutationDefaults({ op: 'update' })(empty-payload skip, explicit-value win), but no ORM caller invoked it for non-empty updates. NowCollection.update,updateAll,updateCount, theupsertupdate branch, and the nested update branch inupdateFirstGraphall call it before compiling the SQL.Collection.createAll([row1, row2, row3])previously generated three differentDatevalues via three independenttimestampNow.generate()calls. ThestableAcrossRowsflag plus per-operationacrossRowsCachereuses one value across all rows that need the default, while per-row generators (cuid,uuidv4) still vary.Test coverage
ts-psl-parity.test.tsasserts byte-identical contracts for Postgres + SQLite from PSL and TS authoring of the same timestamp model, using one shared deterministic-sort comparator helper.interpreter.defaults.test.tscoverstemporal.createdAt()/temporal.updatedAt()happy paths for both targets, the synthetic-preset genericness fixture (AC6), and the misuse cases (PSL_PRESET_NOT_OPTIONAL,PSL_PRESET_AND_DEFAULT_CONFLICT,PSL_PRESET_AND_ID_CONFLICT,PSL_UNKNOWN_FIELD_PRESET).@updatedAtremoval:interpreter.defaults.test.tscovers the migration-hint diagnostic (PSL_UNSUPPORTED_FIELD_ATTRIBUTEenhanced with "Usetemporal.updatedAt()as a field-preset call instead.") and the suppression case (hint omitted when the field already declares anytemporal.*preset).framework-components.authoring.test.tscovers cross-registry collision rejection and the within-registry duplicate-name guard regression.sql-context.test.tscovers create/update/empty-update behavior, the startup-timeMISSING_MUTATION_DEFAULT_GENERATORerror, and theacrossRowsCachecontract (shared cache reuses values across calls; absent cache or non-stableAcrossRowsgenerator regenerates per call).timestampNowdescriptor and runtime generator (new Date()).collection-mutation-defaults.test.tscoverscreateomit/explicit,createAllshared-timestamp + per-row id distinctness,updateAllnon-empty/explicit/empty,updateCountnon-empty/empty, andupsertcreate-branch + empty-update-branch (no advance).Compatibility / risk
@updatedAtattribute removal is a clean deletion. The attribute was added on this branch (commit682714ee) and has never shipped. Users porting Prisma 6 schemas now seePSL_UNSUPPORTED_FIELD_ATTRIBUTEenhanced with a targeted migration hint pointing attemporal.updatedAt(). The hint is suppressed when the field already declares anytemporal.*preset, so users who already migrated aren't told to do what they just did. The hint is implemented as a hardcodedif-branch in the diagnostic emitter — no extensible map.field.createdAt()/field.updatedAt()removed. Also added on this branch and never shipped; replaced byfield.temporal.createdAt()/field.temporal.updatedAt()which consume the same registry entries.@default(now())is unchanged and continues to be the Prisma-6-shaped spelling. Demo apps and example schemas (examples/react-router-demo/prisma/contract.prisma,examples/prisma-next-demo/prisma/schema.prisma) intentionally keep@default(now())— they are not the right surface to advertisetemporal.createdAt().uuidv4,uuidv7,nanoid,cuid2,ulid,ksuid) continue to emit on-create execution defaults; behavior unchanged. NFR4: once PSL gains the field-preset dispatch path (this PR), they become invokable in PSL too — but exposing them is out of scope for this project.stableAcrossRowsflag andacrossRowsCacheparameter are both optional and backward-compatible: omitting them keeps per-call behavior identical to before.Non-goals / out of scope
@createdAtalias.updatedAt.id.uuidv7, etc.) as PSL syntax. The dispatch path supports it; the registry does not enable it in this project.dateTimeparity preset ship here; broader scalar parity tracked separately).PSL_INVALID_TYPE_CONSTRUCTOR_ARITY→PSL_INVALID_NAMESPACED_CALL_ARGUMENTrename. Type-constructor and field-preset arg errors both currently emitPSL_INVALID_ATTRIBUTE_ARGUMENT; the honest rename is a wider refactor deferred to a follow-up (RD11).Summary by CodeRabbit
New Features
createdAtandupdatedAtfield management viafield.temporal.createdAt()andfield.temporal.updatedAt().onCreateandonUpdateseparately).Documentation