Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Sep 14, 2025

Summary by CodeRabbit

  • Bug Fixes

    • More informative validation error messages for invalid inputs.
    • Corrected policy evaluation for auth comparisons across ID fields, improving accuracy in equality/inequality checks.
  • Tests

    • Expanded coverage for nested create/update/delete/upsert and batch updates under policy rules.
    • Adjusted error message expectations in group-by tests.
    • Silenced Prisma push output during test setup.
  • Chores

    • Added zod-validation-error dependency and workspace catalog entry.

Copilot AI review requested due to automatic review settings September 14, 2025 04:27
@coderabbitai
Copy link

coderabbitai bot commented Sep 14, 2025

Walkthrough

Introduces a Zod error formatting utility and integrates it into input validation. Adjusts auth() expression transformation for per-id member comparison. Updates tests for nested policy behaviors and error message expectations. Adds catalog dependency for zod-validation-error and silences Prisma push output in tests.

Changes

Cohort / File(s) Summary
Dependencies & Catalog
packages/runtime/package.json, pnpm-workspace.yaml
Add catalog dependency entry for zod-validation-error and reference it in runtime package dependencies.
Zod Error Formatting Utility
packages/runtime/src/utils/zod-utils.ts
New formatError(error: ZodError): string using zod-validation-error v3/v4 helpers to stringify Zod errors.
Validator Integration
packages/runtime/src/client/crud/validator.ts
Import formatError and change thrown InputValidationError message to use formatted Zod error text.
Policy Expression Transformer
packages/runtime/src/plugins/policy/expression-transformer.ts
Update auth() binary handling to compare per-id members; add helper makeOrAppendMember to build right-hand member paths; keep AND/negation flow.
Client API Test Expectation Tweaks
packages/runtime/test/client-api/group-by.test.ts
Update regex expectations to match quotes: must be in "by".
Policy Nested Mutation Tests
packages/runtime/test/policy/crud/update.test.ts
Expand coverage for nested create/update/delete/upsert/update-many with owner/non-owner scenarios and policy checks.
Test Utilities
packages/runtime/test/utils.ts
Change Prisma db push stdio from inherit to ignore in execSync.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A rabbit taps keys with a hop and a grin,
Zod’s errors now tidy, all tucked neatly in.
auth() finds IDs where members align,
Tests burrow deeper, relations entwine.
With whispers from Prisma kept quiet and slight,
This carrot of polish nibbles just right. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly identifies the two primary fixes in this changeset—Zod error formatting and a 'this' member-access bug—and directly matches the added zod-utils/validator changes and the expression-transformer member-handling updates in the diff, making it concise, relevant, and informative for a reviewer.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/zod-error-format-this-access

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@claude
Copy link

claude bot commented Sep 14, 2025

Claude finished @ymc9's task —— View job


PR Review: Fix zod errors and "this" member access ✅

I've completed my comprehensive review of this pull request. Here's my detailed analysis:

Review Checklist

  • Analyze all changed files
  • Review new zod-utils.ts utility
  • Check validator.ts changes
  • Examine expression-transformer.ts modifications
  • Review test coverage additions
  • Assess code quality and best practices
  • Look for potential bugs or security issues
  • Provide comprehensive feedback

🎯 Summary

This PR addresses two key issues:

  1. Zod error formatting - Improved error messages using zod-validation-error library
  2. "this" member access - Fixed handling of nested member access in policy expressions

✅ Positive Aspects

1. Clean Architecture

  • Well-isolated utility function for Zod error formatting (zod-utils.ts:8-14)
  • Proper version detection logic for backward compatibility with Zod v3/v4

2. Error Handling Improvement

  • The new formatError function in zod-utils.ts provides much better error messages
  • Centralized error formatting eliminates code duplication
  • Single import point in validator.ts:9 keeps changes minimal

3. "This" Member Access Fix

  • The bug fix in expression-transformer.ts:300-306 properly handles nested member access
  • The makeOrAppendMember method correctly appends field names to existing member expressions
  • Prevents incorrect member expressions like this.id instead of this.field.id

4. Comprehensive Test Coverage

  • 376 new lines of tests in update.test.ts covering nested create scenarios
  • Tests verify both policy validation and actual data operations
  • Good coverage of edge cases with owner/non-owner relationship scenarios

🔍 Technical Analysis

Zod Error Formatting (zod-utils.ts)

export function formatError(error: ZodError): string {
    if ('_zod' in error) {
        return fromError4(error).toString();
    } else {
        return fromError3(error).toString();
    }
}
  • ✅ Simple and effective version detection
  • ✅ Proper fallback handling
  • ✅ Clean API design

Expression Transformer Fix (expression-transformer.ts:300-306)

private makeOrAppendMember(other: Expression, fieldName: string): Expression {
    if (ExpressionUtils.isMember(other)) {
        return ExpressionUtils.member(other.receiver, [...other.members, fieldName]);
    } else {
        return ExpressionUtils.member(other, [fieldName]);
    }
}
  • ✅ Correctly handles both simple fields and nested member expressions
  • ✅ Preserves existing member chain when appending
  • ✅ Solves the "this" member access issue described in PR title

🛡️ Security Assessment

  • No security concerns identified
  • Error formatting only improves user experience without exposing sensitive data
  • Expression handling maintains proper access control validation

⚡ Performance Considerations

  • Minimal performance impact
  • Error formatting only runs on validation failures
  • Member access optimization maintains existing query efficiency

📋 Code Quality

  • Excellent code quality
  • Follows existing patterns and conventions
  • Proper TypeScript typing throughout
  • Good separation of concerns

🧪 Test Coverage

The extensive test additions are well-structured:

  • Tests cover real-world scenarios with nested relationships
  • Both positive and negative test cases included
  • Integration with authentication policies properly tested

💡 Minor Suggestions

  1. Documentation: Consider adding JSDoc comments to the new makeOrAppendMember method to explain its purpose in handling nested member access.

  2. Error Handling: The version detection in formatError is robust, but you might consider logging which version is being used for debugging purposes.

🏆 Overall Assessment

This is a high-quality pull request that addresses important functionality issues:

  • Bug Fix: Properly handles "this" member access in complex expressions
  • UX Improvement: Much better error messages for validation failures
  • Backward Compatibility: Supports both Zod v3 and v4
  • Test Coverage: Comprehensive test suite for regression prevention
  • Code Quality: Clean, maintainable, and follows project conventions

The changes are focused, well-tested, and don't introduce any breaking changes. The fix for nested member access is particularly important for policy expressions involving complex object relationships.

Recommendation: ✅ APPROVE


Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes Zod error formatting and resolves an issue with "this" member access in policy expressions. The main changes include introducing a new dependency for better error formatting and fixing policy expression transformation to handle member access correctly.

  • Added zod-validation-error dependency for improved error formatting
  • Fixed policy expression transformer to properly handle "this" member access in auth comparisons
  • Added comprehensive test coverage for nested CRUD operations

Reviewed Changes

Copilot reviewed 8 out of 9 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pnpm-workspace.yaml Added zod-validation-error dependency to catalog
packages/runtime/package.json Added zod-validation-error as runtime dependency
packages/runtime/src/utils/zod-utils.ts New utility for formatting Zod errors with v3/v4 compatibility
packages/runtime/src/client/crud/validator.ts Updated to use new error formatting utility
packages/runtime/src/plugins/policy/expression-transformer.ts Fixed "this" member access issue in auth comparisons
packages/runtime/test/policy/crud/update.test.ts Added extensive test coverage for nested operations
packages/runtime/test/client-api/group-by.test.ts Updated test expectations for new error format
packages/runtime/test/utils.ts Changed stdio setting for cleaner test output
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
packages/runtime/package.json (1)

76-78: Dependency wiring LGTM; add CI matrix for Zod v4 to prevent regressions.

You depend on zod via peer (v3|v4) but dev builds run with Zod v3. Add a CI job that runs runtime tests with Zod v4 to validate zod-utils formatting at runtime.

Would you like me to draft a CI matrix step that installs zod@^4 in the runtime package and runs the test suite?

packages/runtime/test/utils.ts (1)

153-156: Silence Prisma push by default, but keep a debug escape hatch.

Gating stdio behind an env flag preserves quiet tests while enabling ad‑hoc debugging.

 execSync('npx prisma db push --schema ./schema.prisma --skip-generate --force-reset', {
   cwd: workDir,
-  stdio: 'ignore',
+  stdio: process.env.DEBUG_PRISMA_PUSH ? 'inherit' : 'ignore',
 });
packages/runtime/test/policy/crud/update.test.ts (3)

159-187: Duplicate test title; clarify owner vs non‑owner.

Both tests are titled “works with to-one relation check owner side”. This one models the other ownership variant. Rename to avoid confusion.

-        it('works with to-one relation check owner side', async () => {
+        it('works with to-one relation check non-owner side', async () => {

467-470: Make array assertions order-agnostic.

toMatchObject on arrays is order-sensitive. Use arrayContaining to avoid flakiness.

-            ).resolves.toMatchObject({
-                posts: [{ id: 1 }, { id: 2 }],
-            });
+            ).resolves.toMatchObject({
+                posts: expect.arrayContaining([{ id: 1 }, { id: 2 }]),
+            });

601-607: Same: use order-agnostic match for posts.

-            ).resolves.toMatchObject({
-                posts: [{ title: 'Post 1' }, { title: 'Updated Title' }],
-            });
+            ).resolves.toMatchObject({
+                posts: expect.arrayContaining([{ title: 'Post 1' }, { title: 'Updated Title' }]),
+            });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 966018f and 396ca3d.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • packages/runtime/package.json (1 hunks)
  • packages/runtime/src/client/crud/validator.ts (2 hunks)
  • packages/runtime/src/plugins/policy/expression-transformer.ts (2 hunks)
  • packages/runtime/src/utils/zod-utils.ts (1 hunks)
  • packages/runtime/test/client-api/group-by.test.ts (2 hunks)
  • packages/runtime/test/policy/crud/update.test.ts (4 hunks)
  • packages/runtime/test/utils.ts (1 hunks)
  • pnpm-workspace.yaml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
{packages,samples,tests}/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place packages only under packages/, samples/, or tests/

Files:

  • packages/runtime/src/utils/zod-utils.ts
  • packages/runtime/src/client/crud/validator.ts
  • packages/runtime/package.json
  • packages/runtime/test/utils.ts
  • packages/runtime/test/policy/crud/update.test.ts
  • packages/runtime/test/client-api/group-by.test.ts
  • packages/runtime/src/plugins/policy/expression-transformer.ts
pnpm-workspace.yaml

📄 CodeRabbit inference engine (CLAUDE.md)

Use pnpm workspaces for the monorepo

Files:

  • pnpm-workspace.yaml
🧠 Learnings (1)
📚 Learning: 2025-09-04T12:38:14.150Z
Learnt from: CR
PR: zenstackhq/zenstack-v3#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-04T12:38:14.150Z
Learning: Database migrations use Prisma CLI under the hood

Applied to files:

  • packages/runtime/test/utils.ts
🧬 Code graph analysis (3)
packages/runtime/src/client/crud/validator.ts (2)
packages/runtime/src/client/errors.ts (1)
  • InputValidationError (4-8)
packages/runtime/src/utils/zod-utils.ts (1)
  • formatError (8-14)
packages/runtime/test/policy/crud/update.test.ts (1)
packages/runtime/test/policy/utils.ts (1)
  • createPolicyTestClient (14-25)
packages/runtime/src/plugins/policy/expression-transformer.ts (2)
packages/runtime/src/schema/expression.ts (1)
  • ExpressionUtils (16-120)
packages/sdk/src/schema/expression.ts (1)
  • Expression (1-10)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: claude-review
  • GitHub Check: build-test (20.x)
🔇 Additional comments (5)
pnpm-workspace.yaml (1)

16-16: Catalog entry for zod-validation-error looks good.

Aligns with the new runtime dependency and allows central version control via catalog.

packages/runtime/test/client-api/group-by.test.ts (1)

272-272: Updated regex expectations match new formatted messages.

Good alignment with validator’s error formatting and message text.

Also applies to: 283-284

packages/runtime/src/client/crud/validator.ts (1)

9-9: Error formatting integration looks correct.

Import + message composition read well and keep the original error as cause.

Also applies to: 189-190

packages/runtime/src/plugins/policy/expression-transformer.ts (1)

284-291: Fix for auth() equality against member paths is correct.

Appending id-field members on the RHS via makeOrAppendMember properly handles cases like auth() == this.user. The composite-id handling via AND plus final NOT for != is also right.

Please confirm there’s test coverage for:

  • auth() == this with composite auth ids,
  • auth() == this.relation.deep chains.

Also applies to: 300-306

packages/runtime/src/utils/zod-utils.ts (1)

8-14: Keep current discriminator — '_zod' is the documented Zod v4 marker; no change required.
zod-validation-error v4 exposes v3/ and v4/ entry points and Zod's guidance for library authors is to import versioned subpaths and detect Zod‑4 via the "_zod" property, so the existing if ('_zod' in error) branch is appropriate.

Likely an incorrect or invalid review comment.

@ymc9 ymc9 merged commit a7b9ad3 into dev Sep 14, 2025
5 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Sep 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants