Repository navigation
feat(db): land the union schema, indexes and invariants for every stream - #25
Conversation
…domain Three files were growing without bound and every stream needed to append to them, so they became the merge bottleneck for the whole programme. Each is now a directory of per-domain modules with index.ts kept as a pure re-export barrel, so a stream owns one small file instead of contending on one big one. Purely mechanical: no export renamed, no schema or value changed, no import site touched. Equivalence was checked by importing both barrels side by side and comparing export keys, scalar values and every Zod schema serialised through toJSONSchema.
…ream This is the only pull request that touches packages/db for the whole programme, so no other stream ever has to. It carries the union of what all fourteen streams need. Indexes: member(user_id), issue on (team_id, sort_order, id), (team_id, updated_at), (team_id, created_at) and (milestone_id), each partial on archived_at is null, project_team(team_id), and pg_trgm GIN indexes on issue title and description and doc title and content for search. Constraints: issue.parent_id as a self foreign key, author, creator and uploader foreign keys moved from cascade to restrict, label unique per organization and team, a partial unique on pending invitations per organization and lowercased email, and a one parent check on reactions. Every uniqueness rule that coexists with soft delete is written as a partial index conditioned on the delete column now rather than retrofitted later. New tables land empty for later streams to fill: module and its members, issues and links, cycle_progress_snapshot, doc_version, estimate scales and points, issue_identifier_alias, saved_analytics_view, home_widget_preference, recent_visit, favorite, intake and intake_issue, the github and slack sync tables, and webhook with its log.
An issue cannot be its own parent and a parent chain cannot cycle. A cycle cannot end before it starts and cannot overlap another cycle on the same team. Issue relations stay symmetric where the domain says they are. Milestone ordering and its project relationship are checked. Each one throws a typed domain error rather than a bare Error, and each has a test that fails if the invariant is removed.
Why this lands as one pull requestFourteen streams are being built in parallel, and almost every one of them needs a schema change. If each opened its own migration, The same reasoning applies to the three shared barrels. What is in itModule split. 35 new files. Purely mechanical: no export renamed, no value changed, no import site touched. Equivalence was proven by importing both the old and new barrels side by side and comparing export key sets, every scalar value, and all 84 Zod schemas serialised through Indexes. Constraints. Every uniqueness rule that will ever coexist with soft delete is written as a partial index conditioned on the delete column now, rather than being retrofitted once a soft deleted row collides with a live one. New tables, deliberately empty. Invariants, each throwing a typed domain error and each with a test that fails if the invariant is removed: an issue cannot be its own parent and a parent chain cannot cycle, a cycle cannot end before it starts or overlap another on the same team, issue relations stay symmetric where the domain says they are, and milestone ordering is checked against its project. Verification
|
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 32 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (8)
📝 WalkthroughWalkthroughThe PR reorganizes shared constants, events, and validators; expands the PostgreSQL schema and migration metadata; adds cycle-window, issue-parent, relation, and milestone invariants; and makes database reset and ordering behavior deterministic. ChangesDomain foundation
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
packages/shared/src/validators/profile.ts (1)
16-16: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrefer
z.url()hereZod 4 deprecates
z.string().url(), andz.url().max(2048)is equivalent here.♻️ Suggested change
- image: z.string().url().max(2048).nullable(), + image: z.url().max(2048).nullable(),🤖 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/shared/src/validators/profile.ts` at line 16, Update the image validator schema to use Zod 4’s z.url().max(2048) instead of z.string().url().max(2048), while preserving its nullable behavior.packages/db/src/schema/content.ts (1)
121-122: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider the write/storage cost of a GIN trigram index on full document content.
doc_content_trgm_idxindexes the entirecontentbody (andissue_description_trgm_idxmirrors this on issue descriptions). GIN trigram indexes on large free-form text can grow substantially and add write amplification on every insert/update. If content search is expected to be heavy, consider tuningfastupdate/gin_pending_list_limit, or gating trigram search totitle/summarywith a separate strategy (e.g.tsvector) for body search. No change required if this trade-off is already intended.🤖 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/db/src/schema/content.ts` around lines 121 - 122, Review the GIN trigram indexes doc_content_trgm_idx and issue_description_trgm_idx for write and storage impact on full-text fields. If body search does not require trigram indexing, remove or replace those indexes with the intended title/summary or tsvector strategy; otherwise configure the appropriate GIN fastupdate and pending-list settings while preserving the existing search behavior.
🤖 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/core/src/work/cycle-service.ts`:
- Around line 19-42: Protect cycle overlap validation from concurrent writes by
adding a database-level Postgres exclusion constraint for active cycles,
combining team_id with the tstzrange of starts_at and ends_at and excluding
archived rows. Update the cycle schema/migration definitions alongside
assertCycleWindow so inserts and updates for the same team cannot commit
overlapping windows; preserve the existing application-level conflict validation
and exclusion of the current cycle.
In `@packages/shared/src/validators/bootstrap.ts`:
- Around line 4-9: Update the team validator in the bootstrap schema so a
provided value must remain non-empty after trimming, while preserving uppercase
transformation and optional omission when team is not provided. Ensure
whitespace-only inputs are rejected rather than transformed into an empty
string.
In `@packages/shared/src/validators/cycle.ts`:
- Around line 7-8: Update the cycle date fields startsAt and endsAt in the
validation schema so null values fail validation instead of being coerced to the
Unix epoch. Accept only valid date strings or Date instances, or explicitly
preprocess null into a validation failure while preserving normal date
validation.
In `@packages/shared/src/validators/doc.ts`:
- Line 31: Update the includeArchived schema to parse explicit "true" and
"false" string values instead of using z.coerce.boolean(), then transform the
validated value to a boolean while preserving the default of false.
In `@packages/shared/src/validators/issue.ts`:
- Around line 6-14: Update flagSchema so string inputs are validated against
only "true", "false", "1", and "0" before transformation; preserve fallback
behavior for undefined and boolean values, and retain the existing true/1 versus
false/0 conversion. Add validator coverage confirming malformed strings are
rejected for includeArchived and includeSubIssues.
In `@packages/shared/src/validators/organization.ts`:
- Line 14: Update the allowedEmailDomains validator to reject empty entries
after trimming by adding a minimum length of 1 to the string schema between
trim() and max(255), while preserving the existing array limits and lowercase
normalization.
In `@packages/shared/src/validators/team.ts`:
- Around line 7-11: Update the validation message for the key field in the team
schema to state that the first character must be an uppercase letter while
subsequent characters may be uppercase letters or digits, matching
IDENTIFIER_PATTERN.
---
Nitpick comments:
In `@packages/db/src/schema/content.ts`:
- Around line 121-122: Review the GIN trigram indexes doc_content_trgm_idx and
issue_description_trgm_idx for write and storage impact on full-text fields. If
body search does not require trigram indexing, remove or replace those indexes
with the intended title/summary or tsvector strategy; otherwise configure the
appropriate GIN fastupdate and pending-list settings while preserving the
existing search behavior.
In `@packages/shared/src/validators/profile.ts`:
- Line 16: Update the image validator schema to use Zod 4’s z.url().max(2048)
instead of z.string().url().max(2048), while preserving its nullable behavior.
🪄 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.yaml
Review profile: CHILL
Plan: Pro
Run ID: 40e2c430-8122-4f8a-8469-e54791f0ea6d
📒 Files selected for processing (58)
apps/mcp/src/test-helpers.tspackages/core/src/test-support.tspackages/core/src/work/cycle-service.test.tspackages/core/src/work/cycle-service.tspackages/core/src/work/issue-invariants.test.tspackages/core/src/work/issue-service.tspackages/core/src/work/milestone-service.test.tspackages/core/src/work/milestone-service.tspackages/db/drizzle.config.tspackages/db/drizzle/0000_shallow_richard_fisk.sqlpackages/db/drizzle/meta/0000_snapshot.jsonpackages/db/drizzle/meta/_journal.jsonpackages/db/package.jsonpackages/db/src/ensure-extensions.tspackages/db/src/schema/auth.tspackages/db/src/schema/comms.tspackages/db/src/schema/content.tspackages/db/src/schema/index.test.tspackages/db/src/schema/org.tspackages/db/src/schema/work.tspackages/shared/src/constants/actor.tspackages/shared/src/constants/doc.tspackages/shared/src/constants/estimate.tspackages/shared/src/constants/index.tspackages/shared/src/constants/issue.tspackages/shared/src/constants/notification.tspackages/shared/src/constants/ordering.tspackages/shared/src/constants/organization.tspackages/shared/src/constants/pattern.tspackages/shared/src/constants/project.tspackages/shared/src/constants/upload.tspackages/shared/src/constants/workflow-state.tspackages/shared/src/events/actor.tspackages/shared/src/events/channel.tspackages/shared/src/events/connection.tspackages/shared/src/events/index.tspackages/shared/src/events/message.tspackages/shared/src/events/presence.tspackages/shared/src/events/scope.tspackages/shared/src/events/sync.tspackages/shared/src/validators/auth.tspackages/shared/src/validators/bootstrap.tspackages/shared/src/validators/comment.tspackages/shared/src/validators/common.tspackages/shared/src/validators/cycle.tspackages/shared/src/validators/doc.tspackages/shared/src/validators/index.tspackages/shared/src/validators/issue.tspackages/shared/src/validators/label.tspackages/shared/src/validators/milestone.tspackages/shared/src/validators/notification.tspackages/shared/src/validators/organization.tspackages/shared/src/validators/profile.tspackages/shared/src/validators/project.tspackages/shared/src/validators/team.tspackages/shared/src/validators/upload.tspackages/shared/src/validators/view.tspackages/shared/src/validators/workflow-state.ts
Splitting the barrels put these under review and each one is a real defect. z.coerce.date() turns null into 1970-01-01, so a create request with a null cycle date persisted an unintended boundary rather than failing. Cycle dates now accept only a non empty string or a Date. z.coerce.boolean() treats the string "false" as truthy, so a caller passing includeArchived=false got archived docs back. Boolean query flags now accept only true, false, 1 and 0, and anything else is rejected instead of silently reading as false. A blank team selector no longer parses to an empty string, a blank allowed email domain is rejected, and the team key message now says the first character must be a letter, which the regex has always required. Serialise the cycle overlap check with a transaction scoped advisory lock keyed on the team. The check read then wrote inside a transaction with nothing holding a lock in between, so two concurrent requests could both pass and commit overlapping cycles. Drizzle cannot express a Postgres EXCLUDE constraint and the development flow is db:push rather than migrations, so a raw constraint would drift; the advisory lock closes the race everywhere.
Split the shared barrels by domain and land the union of every table, index, constraint and invariant the remaining thirteen streams need, so no other stream has to touch packages/db.