Skip to content

feat(db): land the union schema, indexes and invariants for every stream - #25

Merged
pulkitxm merged 5 commits into
mainfrom
feat/s3-schema
Jul 23, 2026
Merged

pulkitxm merged 5 commits into
mainfrom
feat/s3-schema

Conversation

@pulkitxm

Copy link
Copy Markdown
Member

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.

pulkitxm added 3 commits July 23, 2026 21:54
…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.
@pulkitxm

Copy link
Copy Markdown
Member Author

Why this lands as one pull request

Fourteen streams are being built in parallel, and almost every one of them needs a schema change. If each opened its own migration, packages/db becomes a permanent merge conflict and the migration order becomes a coordination problem. So this carries the union of everything up front, and packages/db is then closed for the rest of the programme.

The same reasoning applies to the three shared barrels. validators/index.ts, constants/index.ts and events/index.ts were files every stream needed to append to. They are now directories of per-domain modules with the barrel kept as a pure re-export, so a stream owns validators/cycle.ts instead of queueing behind thirteen others on one file.

What is in it

Module 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 z.toJSONSchema. Identical.

Indexes. member(user_id), which resolveMembership hits on every API request and every page render and which previously sequential scanned. 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). The pg_trgm extension plus GIN trigram indexes on issue title and description and doc title and content, so search does not have to be added later as a second migration.

Constraints. issue.parent_id as a real self referencing foreign key. Author, creator and uploader foreign keys moved from cascade to restrict, so deleting a user can no longer silently delete their comments and attachments. Label uniqueness per organization and team. A partial unique on pending invitations per organization and lowercased email, which is what stops the duplicate invite path. A one parent check on reactions.

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. module with its members, issues and links, cycle_progress_snapshot, doc_version, estimate_scale and estimate_point, 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. Later streams fill them without reopening this package.

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

bun run verify green on top of the merged Bun main. I also queried the live database rather than reading the TypeScript, and confirmed every new table actually exists after bun run db:push.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 32 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5519933c-0fea-4cd4-affb-3105c4d12a46

📥 Commits

Reviewing files that changed from the base of the PR and between 03de1c5 and c36d4b6.

📒 Files selected for processing (8)
  • packages/core/src/work/cycle-service.ts
  • packages/shared/src/validators/bootstrap.ts
  • packages/shared/src/validators/cycle.ts
  • packages/shared/src/validators/doc.ts
  • packages/shared/src/validators/issue.ts
  • packages/shared/src/validators/organization.ts
  • packages/shared/src/validators/team.ts
  • packages/shared/src/validators/validators.test.ts
📝 Walkthrough

Walkthrough

The 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.

Changes

Domain foundation

Layer / File(s) Summary
Shared contracts and validation
packages/shared/src/constants/*, packages/shared/src/events/*, packages/shared/src/validators/*
Domain constants, Zod event schemas, request validators, inferred input types, and barrel exports are split into feature-specific modules.
Postgres schema and migration artifacts
packages/db/drizzle/*, packages/db/src/schema/*, packages/db/src/schema/index.test.ts, packages/db/src/ensure-extensions.ts, packages/db/package.json
The database schema adds domain tables, relationships, indexes, enums, sequences, sync fields, deletion rules, search indexes, and schema invariant tests.
Cycle window validation
packages/core/src/work/cycle-service.ts, packages/core/src/work/cycle-service.test.ts
Cycle creation and updates reject invalid or overlapping active windows while allowing boundary-touching windows and overlaps across different teams.
Issue parent and relation invariants
packages/core/src/work/issue-service.ts, packages/core/src/work/issue-invariants.test.ts
Issue parent assignments reject loops, missing parents, and excessive chain depth; relation inverse mappings and symmetric writes/removals are covered by tests.
Milestone ordering and reordering
packages/core/src/work/milestone-service.ts, packages/core/src/work/milestone-service.test.ts
Milestone ordering uses descending lookup and creation-time tie breaks, while reorder requests require an exact, duplicate-free project milestone set.
Deterministic database reset
apps/mcp/src/test-helpers.ts, packages/core/src/test-support.ts
Database reset table discovery orders pg_tables results by table name before truncation.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Noveum/orbit#4: Introduces the core work-domain service implementations touched by the invariant changes.
  • Noveum/orbit#9: Introduces the database reset helper whose truncation ordering is updated here.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the schema, index, and invariant work across shared barrels and database streams.
Description check ✅ Passed The description is clearly related to the changeset and describes the barrel split plus the shared database and invariant work.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/s3-schema

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (2)
packages/shared/src/validators/profile.ts (1)

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

Prefer z.url() here

Zod 4 deprecates z.string().url(), and z.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 win

Consider the write/storage cost of a GIN trigram index on full document content.

doc_content_trgm_idx indexes the entire content body (and issue_description_trgm_idx mirrors 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 tuning fastupdate/gin_pending_list_limit, or gating trigram search to title/summary with 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5fa3ac9 and 03de1c5.

📒 Files selected for processing (58)
  • apps/mcp/src/test-helpers.ts
  • packages/core/src/test-support.ts
  • packages/core/src/work/cycle-service.test.ts
  • packages/core/src/work/cycle-service.ts
  • packages/core/src/work/issue-invariants.test.ts
  • packages/core/src/work/issue-service.ts
  • packages/core/src/work/milestone-service.test.ts
  • packages/core/src/work/milestone-service.ts
  • packages/db/drizzle.config.ts
  • packages/db/drizzle/0000_shallow_richard_fisk.sql
  • packages/db/drizzle/meta/0000_snapshot.json
  • packages/db/drizzle/meta/_journal.json
  • packages/db/package.json
  • packages/db/src/ensure-extensions.ts
  • packages/db/src/schema/auth.ts
  • packages/db/src/schema/comms.ts
  • packages/db/src/schema/content.ts
  • packages/db/src/schema/index.test.ts
  • packages/db/src/schema/org.ts
  • packages/db/src/schema/work.ts
  • packages/shared/src/constants/actor.ts
  • packages/shared/src/constants/doc.ts
  • packages/shared/src/constants/estimate.ts
  • packages/shared/src/constants/index.ts
  • packages/shared/src/constants/issue.ts
  • packages/shared/src/constants/notification.ts
  • packages/shared/src/constants/ordering.ts
  • packages/shared/src/constants/organization.ts
  • packages/shared/src/constants/pattern.ts
  • packages/shared/src/constants/project.ts
  • packages/shared/src/constants/upload.ts
  • packages/shared/src/constants/workflow-state.ts
  • packages/shared/src/events/actor.ts
  • packages/shared/src/events/channel.ts
  • packages/shared/src/events/connection.ts
  • packages/shared/src/events/index.ts
  • packages/shared/src/events/message.ts
  • packages/shared/src/events/presence.ts
  • packages/shared/src/events/scope.ts
  • packages/shared/src/events/sync.ts
  • packages/shared/src/validators/auth.ts
  • packages/shared/src/validators/bootstrap.ts
  • packages/shared/src/validators/comment.ts
  • packages/shared/src/validators/common.ts
  • packages/shared/src/validators/cycle.ts
  • packages/shared/src/validators/doc.ts
  • packages/shared/src/validators/index.ts
  • packages/shared/src/validators/issue.ts
  • packages/shared/src/validators/label.ts
  • packages/shared/src/validators/milestone.ts
  • packages/shared/src/validators/notification.ts
  • packages/shared/src/validators/organization.ts
  • packages/shared/src/validators/profile.ts
  • packages/shared/src/validators/project.ts
  • packages/shared/src/validators/team.ts
  • packages/shared/src/validators/upload.ts
  • packages/shared/src/validators/view.ts
  • packages/shared/src/validators/workflow-state.ts

Comment thread packages/core/src/work/cycle-service.ts Resolved
Comment thread packages/shared/src/validators/cycle.ts Resolved
Comment thread packages/shared/src/validators/doc.ts Resolved
Comment thread packages/shared/src/validators/issue.ts Resolved
Comment thread packages/shared/src/validators/team.ts Resolved
pulkitxm added 2 commits July 23, 2026 22:13
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.
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.

1 participant