test: batch A — schema.ts mutation hardening (0% → 100%) - #110
Conversation
🤖 CodeAnt AI — Review Status
|
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
✅ Deploy Preview for moderaty ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughChangesSchema Mutation Coverage
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Sequence DiagramThis PR adds metadata-driven tests that re-import the database schema and verify its tables, columns, constraints, indexes, defaults, and checks. Equivalent schema mutants are explicitly excluded while meaningful mutations are detected by the shape tests. sequenceDiagram
participant Tests
participant Schema
participant Drizzle
Tests->>Schema: Re-import schema for each test
Schema->>Drizzle: Define database tables and constraints
Tests->>Drizzle: Read schema metadata
Drizzle-->>Tests: Return table and constraint definitions
Tests->>Tests: Verify names defaults keys and indexes
Tests-->>Tests: Record mutation as killed or equivalent
Generated by CodeAnt AI |
|
There was a problem hiding this comment.
This PR achieves 100% mutation score for schema.ts (137 killed, 33 justified equivalents) through comprehensive schema validation tests. All changes are well-executed:
- schema.test.ts: Thorough metadata-based validation using
getTableConfigto verify table/column names, constraints, foreign keys, indexes, and defaults - schema.ts: Properly documented equivalent-mutant exclusions with clear justification
- mutation-80-backlog.md: Accurate tracking of batch A completion
The PR includes successful verification (npx stryker run, all tests pass, npm run check, Codacy clean). Ready to merge.
You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.
🏁 CodeAnt Quality Gate ResultsCommit: ✅ Overall Status: PASSEDQuality Gate Details
|
Not up to standards ⛔🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | ✅ 59 (≤ 100 complexity) |
| Duplication |
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
PR Summary by QodoMutation testing: harden Drizzle schema contract to reach 100% detection
AI Description
Diagram
High-Level Assessment
Files changed (3)
|
There was a problem hiding this comment.
Warning
CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.
Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.
Actionable comments posted: 1
🤖 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 `@src/lib/server/db/schema.test.ts`:
- Around line 64-65: Update expectColumns so the hasDefault assertion always
runs for every column, using false when shape.hasDefault is undefined. Preserve
explicitly provided hasDefault values while ensuring columns such as users.id,
sessions.expires_at, and channels.tone_level fail the test if they unexpectedly
have a default.
🪄 Autofix
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: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: ac9929ac-6013-4e73-8558-8498d684979d
📒 Files selected for processing (3)
docs/mutation-80-backlog.mdsrc/lib/server/db/schema.test.tssrc/lib/server/db/schema.ts
| if (shape.hasDefault !== undefined) | ||
| expect(column.hasDefault, `${config.name}.${column.name} hasDefault`).toBe(shape.hasDefault); |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
Assert hasDefault for every column, not only when declared.
expectColumns checks hasDefault only when the expectation supplies it. Columns such as users.id, sessions.expires_at, and channels.tone_level therefore have no hasDefault assertion. Default hasDefault to false so an unexpected default fails the test.
♻️ Proposed change
- if (shape.hasDefault !== undefined)
- expect(column.hasDefault, `${config.name}.${column.name} hasDefault`).toBe(shape.hasDefault);
+ expect(column.hasDefault, `${config.name}.${column.name} hasDefault`).toBe(
+ shape.hasDefault ?? false
+ );📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (shape.hasDefault !== undefined) | |
| expect(column.hasDefault, `${config.name}.${column.name} hasDefault`).toBe(shape.hasDefault); | |
| expect(column.hasDefault, `${config.name}.${column.name} hasDefault`).toBe( | |
| shape.hasDefault ?? 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 `@src/lib/server/db/schema.test.ts` around lines 64 - 65, Update expectColumns
so the hasDefault assertion always runs for every column, using false when
shape.hasDefault is undefined. Preserve explicitly provided hasDefault values
while ensuring columns such as users.id, sessions.expires_at, and
channels.tone_level fail the test if they unexpectedly have a default.
Code Review by Qodo
1. Brittle schema SQL assertions
|
| function expectColumns(table: SQLiteTable, expected: Record<string, ColumnShape>): void { | ||
| const config = getTableConfig(table); | ||
| expect(config.columns.map((c) => c.name)).toEqual(Object.keys(expected)); | ||
| for (const column of config.columns) { |
There was a problem hiding this comment.
1. Brittle schema sql assertions 🐞 Bug ⚙ Maintainability
schema.test.ts asserts exact SQL serialization output and ordered column lists from Drizzle metadata, so semantically equivalent changes in Drizzle’s formatting/ordering can fail CI without any actual schema contract change. This is especially likely to surface during routine drizzle-orm minor bumps since the dependency is specified with a caret range.
Agent Prompt
### Issue description
`src/lib/server/db/schema.test.ts` makes a few assertions that are sensitive to Drizzle internals (SQL serialization formatting and metadata ordering). This can break tests on semantically equivalent changes (e.g., whitespace/casing/quoting changes in `sqlToQuery`, or non-contractual reordering of `getTableConfig(...).columns`).
### Issue Context
These tests are intended to harden the schema contract, but not every assertion needs to be byte-for-byte stable. Where formatting/order is not part of the contract, the test should assert semantic equivalence instead.
### Fix Focus Areas
- src/lib/server/db/schema.test.ts[44-47]
- src/lib/server/db/schema.test.ts[56-59]
- src/lib/server/db/schema.test.ts[74-80]
- src/lib/server/db/schema.test.ts[262-270]
- src/lib/server/db/schema.test.ts[366-375]
### Suggested changes
- For column lists, compare unordered names when order is not explicitly contractual (e.g., sort both arrays before comparing, or compare as sets).
- For SQL text checks where formatting is not the contract, normalize before comparing (e.g., collapse whitespace and optionally standardize casing), or use `toMatch` with a precise regex that tolerates harmless formatting changes.
- Keep exact-string assertions only for cases where the emitted SQL text itself is intentionally pinned as part of the project’s schema contract.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools




User description
Behavior
First kill batch of the mutation-80% push (tracker:
docs/mutation-80-backlog.md, baseline PR #108).src/lib/server/db/schema.tswas the worst file in the baseline: 170 survived / 0 killed (0.0%). After this PR: 137 killed, 0 survived, 33 ignored — 100.00%.What changed
src/lib/server/db/schema.test.ts(18 tests): asserts the full Drizzle schema shape viagetTableConfig— table/column names, notNull, primary keys (composite + autoincrement), FKs withonDelete, unique constraints, indexes (incl. the partial consents retention index and its WHERE clause), thechannels_org_requires_ownerCHECK SQL, flag defaults, and the exactcreated_atdefault expression viaSQLiteSyncDialect.sqlToQuery. Explicit assertions, no snapshots.schema.ts: a StringLiteral""on a column db name that equals the property key is a no-op — drizzle treats an empty name as falsy and falls back to the property key (verified by hand on drizzle-orm 0.45.2). Each carries a per-line// Stryker disable next-line StringLiteraldirective with the reason; two directives share lines with.default('free')and also ignore that mutant (the default stays pinned by the shape test). Documented in the backlog triage log.perTest coverage-attribution gotcha (recorded in the triage log)
The first scoped run killed only 21/170: Stryker's
perTestcoverage attributes module-top-level mutants only to tests that execute the module body, and a static import attributes everything to whichever test loads the module first. Re-importing the schema per test (vi.resetModules()+ dynamicimport(), the idiom fromindex.test.ts) fixed attribution → 139 killed. This also means the full-suite baseline undercounts kills for declarative module-scope code elsewhere.Verification
npx stryker run --mutate "src/lib/server/db/schema.ts" --ignoreStatic→ 100.00% (137 killed / 0 survived / 33 ignored); every kill is a survived→killed flip against the baseline runnpm run test— 551/551 passnpm run check— 0 errors, 0 warningscodacy-analysis analyze --files src/lib/server/db/schema.ts src/lib/server/db/schema.test.ts— 0 issuesOverall-score impact
schema.ts valid mutants: 170 → 137, all detected. Estimated overall: ~77.8% (from 72.76% baseline). Batches B–E continue per the backlog.
CodeAnt-AI Description
Lock down the database schema with comprehensive mutation tests
What Changed
Impact
✅ Fewer undetected database schema regressions✅ Safer cascading deletes and tenant data separation✅ Reliable defaults and indexes for stored data💡 Usage Guide
Checking Your Pull Request
Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.
Talking to CodeAnt AI
Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
Preserve Org Learnings with CodeAnt
You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
Check Your Repository Health
To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.