Skip to content

Enterprise Stabilization and Production Hardening#29

Merged
aish-am22 merged 2 commits into
mainfrom
enterprise-stabilization-v1-3840965338026074549
Jun 8, 2026
Merged

Enterprise Stabilization and Production Hardening#29
aish-am22 merged 2 commits into
mainfrom
enterprise-stabilization-v1-3840965338026074549

Conversation

@aish-am22

@aish-am22 aish-am22 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

This submission transforms the application from a prototype into a production-ready enterprise legal AI platform.

Key architectural changes:

  1. Infrastructure: Introduced a multi-stage Dockerfile and Docker Compose to support persistent background workers and Redis, solving the 500 errors caused by Vercel's serverless timeouts.
  2. Security: Refactored the entire database access layer to use withTransaction, ensuring that Row Level Security (RLS) variables are correctly scoped and connections are released immediately, solving pool exhaustion issues.
  3. Resilience: AI agents and RAG pipelines now use an exponential backoff retry mechanism to handle transient API failures or rate limits from Google Gemini.
  4. Compliance: Added audit logging for document exports, redline approvals/rejections, and report sharing.
  5. Observability: Integrated Sentry for real-time error tracking and added a health check endpoint for uptime monitoring.

PR created automatically by Jules for task 3840965338026074549 started by @aish-am22

Summary by CodeRabbit

Release Notes

  • New Features

    • Added health check endpoint for monitoring system status
    • Enhanced audit logging for document exports, redline actions, and report sharing
  • Improvements

    • Improved system reliability with automatic retry mechanisms for external API calls
    • Added error monitoring and performance tracking integration
    • Implemented containerization for simplified deployment
  • Infrastructure

    • Docker and docker-compose support for streamlined deployment and local development

- Fixed critical 500 errors by adding missing imports in AI routes.
- Migrated from serverless-incompatible BullMQ setup to a containerized Docker architecture.
- Hardened database security by refactoring RLS session management to use transaction-scoped variables (preventing session leakage).
- Implemented exponential backoff retry logic for all AI API interactions (Gemini/RAG).
- Added comprehensive compliance audit logging for sensitive document actions (exports, redlines).
- Integrated Sentry (v10+) for error tracking and added a /api/health monitoring endpoint.
- Optimized PGVector HNSW index parameters for production-scale legal document retrieval.
- Added environment variable validation to prevent startup with misconfigured secrets.

Co-authored-by: aish-am22 <146462239+aish-am22@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel

vercel Bot commented Jun 8, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
cookie-care Ready Ready Preview, Comment Jun 8, 2026 5:44am

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@aish-am22, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 49 minutes and 9 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

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.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5d9e1e6a-eef8-4c12-9a72-036937c1fa2e

📥 Commits

Reviewing files that changed from the base of the PR and between f6c173d and efea264.

📒 Files selected for processing (2)
  • backend/src/controllers/folders.ts
  • backend/src/controllers/libraryItems.ts
📝 Walkthrough

Walkthrough

This pull request refactors the backend to decouple authentication from database transaction management, adds observability and resilience infrastructure, and introduces compliance auditing. The middleware no longer manages per-request RLS setup; instead, controllers and services explicitly invoke withTransaction to scope database operations with proper user context. Sentry monitoring, environment validation, retry logic for transient API failures, audit logging for document operations, and deployment configurations complete the infrastructure hardening.

Changes

Database Transaction Architecture & Resilience Refactor

Layer / File(s) Summary
Retry utility and exponential backoff foundation
backend/src/utils/retry.ts
Adds withRetry<T>() async utility that wraps functions to retry on transient errors (socket hangs, fetch failures, 503/504, 429) with exponential backoff doubling and console logging of remaining attempts.
Environment validation and Sentry monitoring setup
backend/src/config/validate.ts, backend/src/config/sentry.ts, package.json
Introduces validateEnv() to enforce required environment variables (DATABASE_URL, GEMINI_API_KEY, ENCRYPTION_KEY, conditional REDIS_URL), validates ENCRYPTION_KEY length to exactly 32 bytes, and adds initSentry(app) and initSentryErrorHandler(app) for conditional Sentry initialization with tracesSampleRate: 1.0 performance monitoring. Adds @sentry/node and @sentry/profiling-node ^10.56.0 to dependencies.
Server startup with validation and error monitoring
server.ts
Calls validateEnv() at server startup and wires initSentry(app) before middleware and initSentryErrorHandler(app) after routes, ensuring environment validation and error monitoring are established early.
Middleware simplification and transaction delegation
backend/src/middleware/auth.ts
Removes per-request database client setup, RLS session configuration via set_config, transaction wrapping, and cleanup handlers from authenticateToken, delegating all transaction/RLS concerns to individual route handlers via withTransaction.
Admin controller transaction refactoring
backend/src/controllers/admin.ts
Refactors approveUser, getAllUsers, and getPendingUsers to execute database operations inside withTransaction(userId, userRole, ...) callbacks, replacing direct req.dbClient || pool queries and deriving user context from req.user.
Folders, jobs, and library items controllers transaction refactoring
backend/src/controllers/folders.ts, backend/src/controllers/jobs.ts, backend/src/controllers/libraryItems.ts
Refactors getFolders, createFolder, deleteFolder; getJobs, getJobById; and getLibraryItems, createLibraryItem, deleteLibraryItem to wrap all database operations in withTransaction(userId, userRole, ...) with error handling and status code mapping (404 for "not found" errors, 500 for others).
Document and redline operations with transactions and audit logging
backend/src/controllers/documents.ts
Refactors getDocuments, getDocumentById, createDocument, uploadDocument to use withTransaction; updates createRedline to throw "Document not found" error when absent; wraps acceptRedline and rejectRedline redline updates plus new compliance_audit_logs inserts (redline_accept, redline_reject) inside withTransaction; and adds conditional compliance_audit_logs entry (document_export) to exportDocument.
Agent and RAG services transaction patterns
backend/src/agents/legalAgent.ts
Updates AgentOrchestrator.runAnalysis and interactAnalyze to begin explicit transactions with SET LOCAL app.current_user_id and SET LOCAL app.current_user_role = 'ADMIN' when no dbClient is provided (replacing prior set_config calls) and adds commit/rollback handling scoped to transaction ownership.
RAG service transaction setup and retry-wrapped Gemini calls
backend/src/RAG/ragService.ts
Updates chunkAndIndexDocument to start transactions earlier with SET LOCAL app.current_user_role = 'ADMIN', adjusts commit/rollback handling, and wraps both embedding generation and semantic re-ranking Gemini calls in withRetry for resilience against transient failures.
Job queue state management with transactions
backend/src/services/jobQueue.ts
Reworks updateJobState helper to use dedicated pooled client with explicit transaction, SET LOCAL app.current_user_role = 'ADMIN', and proper client release in finally block (replacing prior direct pool.query), and wraps Gemini refinement calls in withRetry.
RLS policy formatting and HNSW index tuning
backend/src/config/initDb.ts
Reformats RLS policy USING clause to explicitly parenthesize owner-column and ADMIN role predicates, and updates legal_document_chunks HNSW index creation with explicit build parameters (m = 16, ef_construction = 64).
Compliance audit logging for reports
backend/src/controllers/reports.ts
Adds shareReportEmail transactional compliance_audit_logs insert with action_type = 'report_share' and recipient email, report title, and format metadata before email dispatch.
Health check and route wiring
backend/src/routes/index.ts, backend/src/routes/analyze.ts, backend/src/routes/drafting.ts, backend/src/routes/lawyer.ts
Adds GET /health endpoint that performs database connectivity check via pool.query("SELECT 1"), reports UP status with computed latency on success or DOWN status with 503 on failure, and wires missing addJobToQueue imports to analyze, drafting, and lawyer routes.
Multi-stage Dockerfile and Docker Compose
Dockerfile, docker-compose.yml
Adds multi-stage Dockerfile using Node.js 22 (builder stage: Playwright system deps, npm install, source copy, build; runner stage: minimal deps, built artifacts, Playwright Chromium, port 3000 exposure, npm start entrypoint) and docker-compose.yml defining app (built from source, port 3000, environment config, depends on redis, restart: always) and redis (Redis 7 Alpine, port 6379, restart: always) services.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • aish-am22/CookieCare#26: The main PR's updates to backend/src/agents/legalAgent.ts (starting an explicit transaction and setting app.current_user_id/app.current_user_role for RLS-scoped behavior when no dbClient is provided) directly build on the retrieved PR's legalAgent RLS hardening that changes access control to current_setting(...)/ADMIN role checks and threads/accepts an optional dbClient.
  • aish-am22/CookieCare#25: Both PRs modify the same backend transaction/RLS flow in controllers (e.g., getDocuments/getFolders/getLibraryItems switching to withTransaction) and also touch backend/src/RAG/ragService.ts's reRankResults behavior.
  • aish-am22/CookieCare#27: Both PRs modify the auth/session middleware and the same DB-reading controllers (notably backend/src/middleware/auth.ts cleanup/release logic and backend/src/controllers/libraryItems.ts / documents.ts error-handling paths), so the changes overlap at the code level.

Poem

🐰 A rabbit hops through transactions, each one so neat,
With retries and health checks, the backend's complete!
Sentry logs errors while Docker contains the whole show,
Audits track redlines as data flows free and slow.
Infrastructure strengthened—let the foundation now grow! 🌱

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Enterprise Stabilization and Production Hardening' directly aligns with the PR's core objectives, which transform the application into production-ready with infrastructure, security, resilience, compliance, and observability improvements.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch enterprise-stabilization-v1-3840965338026074549

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.

- Expanded compliance audit logs to include document deletions and library item deletions.
- Refined background worker RLS context to ensure atomic transactions.
- Finalized Sentry v10 integration with correct Express middleware.
- Completed full controller refactor to use transaction-scoped RLS sessions.

Co-authored-by: aish-am22 <146462239+aish-am22@users.noreply.github.com>
@aish-am22 aish-am22 merged commit de02fac into main Jun 8, 2026
2 of 3 checks passed
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