Skip to content

refactor: unify Redis access, wire ingest pipeline, consolidate auth#61

Open
williaby wants to merge 2 commits into
mainfrom
claude/repo-architecture-review-n7rlg
Open

refactor: unify Redis access, wire ingest pipeline, consolidate auth#61
williaby wants to merge 2 commits into
mainfrom
claude/repo-architecture-review-n7rlg

Conversation

@williaby
Copy link
Copy Markdown
Contributor

Summary

Implements the top-3 refactors from the repository architecture & maintainability review. Each is incremental and test-backed; the full suite stays green throughout.

🥇 #1 — Unified Redis access + non-blocking reads

  • New core/redis.py: a single pooled, synchronous client factory (separate decoded and raw pools — RQ requires raw bytes) replacing three hand-rolled redis.Redis(...) constructions in queue/client, queue/redis_store, and websocket/events. Pools are disconnected on FastAPI shutdown.
  • Fixed event-loop blocking: added get_batch_status_async / get_job_status_async that offload synchronous Redis calls via asyncio.to_thread; the async API and WebSocket handlers now await them instead of calling sync Redis directly on the loop.
  • Deduped _parse_iso_datetime across both models → the existing utils.time_utils.parse_iso_datetime.

🥈 #2 — Completed the ingest → persist → enqueue flow

  • ingest_files now persists the batch/jobs and enqueues them (enqueue_batch_jobs), removing the long-standing TODO that left the pipeline non-functional end-to-end. Gated behind a new default-off enqueue_enabled setting for safe rollout, with best-effort rollback + 503 on infra failure.
  • Hardened process_job_task: pipeline failures now mark the job FAILED and refresh batch progress instead of crashing the worker / leaving the batch stuck in PROCESSING.

🥉 #3 — Consolidated authentication + wired exception hierarchy

  • Extracted shared JWKS-load (now guarded by an asyncio.Lock to prevent fetch stampedes on cache miss), key-resolution, and JWT-decode helpers. The WebSocket path now shares the middleware's clock-skew leeway — fixing a divergence where HTTP and WS accepted different tokens.
  • Registered a FastAPI handler mapping ProjectBaseError subclasses to HTTP responses via http_status_for, making the previously-unused centralized exception hierarchy live.

Verification

Gate Result
Tests 446 passed, 1 skipped (+28 new)
Coverage 91.59% (gate: 80%)
ruff check + format clean
basedpyright 0 errors
bandit 0 high/critical (pre-existing low/medium only)

Scope notes (transparent deferrals)

  • Existing HTTPException call sites in handlers were kept rather than migrated to domain exceptions — that would change response-body contracts and break current tests. The hierarchy is now wired and tested; migrating call sites is a clean follow-up.
  • The async refactor uses to_thread offload rather than a full async-Redis rewrite, because RQ requires a synchronous client shared with the worker — a parallel async implementation would reintroduce the duplication this PR removes.

Test plan

  • uv run pytest — 446 passed, 1 skipped
  • uv run ruff check . / ruff format --check
  • uv run basedpyright src/ — 0 errors
  • uv run bandit -r src — 0 high/critical
  • Coverage ≥ 80% (actual 91.59%)

https://claude.ai/code/session_01PA6dtgMhfzSe22VVtqBfxE


Generated by Claude Code

Implements the top-3 refactors from the architecture review.

1. Unify Redis access + non-blocking reads
   - Add core/redis.py: single pooled, synchronous client factory
     (decoded + raw pools) replacing three hand-rolled redis.Redis(...)
     constructions in queue/client, queue/redis_store and websocket/events.
   - Close pools on FastAPI shutdown lifespan.
   - Add async, thread-offloaded wrappers (get_batch_status_async /
     get_job_status_async) and switch async API/WebSocket handlers to them
     so synchronous Redis calls no longer block the event loop.
   - Dedupe _parse_iso_datetime in models to utils.time_utils.parse_iso_datetime.

2. Complete ingest -> persist -> enqueue flow
   - ingest_files now persists the batch/jobs and enqueues them via
     enqueue_batch_jobs, gated behind the new (default-off) enqueue_enabled
     setting, with best-effort rollback + 503 on failure.
   - Harden process_job_task: pipeline failures mark the job FAILED and
     refresh batch progress instead of crashing the worker.

3. Consolidate authentication + wire exception hierarchy
   - Extract shared JWKS load (with asyncio.Lock to prevent fetch stampede),
     key resolution and JWT decode helpers; the WebSocket path now shares the
     middleware's clock-skew leeway (previously divergent).
   - Register a FastAPI handler mapping ProjectBaseError subclasses to HTTP
     responses via http_status_for, making the centralized exception
     hierarchy live.

Adds tests for the Redis factory, async wrappers, worker failure handling,
ingest enqueue wiring + rollback, leeway consistency, and exception mapping.
Full suite: 446 passed, coverage 91.59%.

https://claude.ai/code/session_01PA6dtgMhfzSe22VVtqBfxE
Copilot AI review requested due to automatic review settings May 30, 2026 01:31
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 30, 2026

Warning

Review limit reached

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

More reviews will be available in 34 minutes and 15 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: fc256eba-0e99-4e71-8737-6bb0eefa7641

📥 Commits

Reviewing files that changed from the base of the PR and between fe8761e and 453eaa4.

📒 Files selected for processing (21)
  • src/rag_processor/api/batch.py
  • src/rag_processor/api/ingest.py
  • src/rag_processor/auth/cloudflare.py
  • src/rag_processor/core/config.py
  • src/rag_processor/core/exceptions.py
  • src/rag_processor/core/redis.py
  • src/rag_processor/main.py
  • src/rag_processor/models/batch.py
  • src/rag_processor/models/job.py
  • src/rag_processor/queue/client.py
  • src/rag_processor/queue/jobs.py
  • src/rag_processor/queue/redis_store.py
  • src/rag_processor/websocket/events.py
  • src/rag_processor/websocket/router.py
  • tests/integration/test_e2e_flow.py
  • tests/unit/test_auth_cloudflare.py
  • tests/unit/test_core_redis.py
  • tests/unit/test_exception_handler.py
  • tests/unit/test_ingest.py
  • tests/unit/test_jobs_async.py
  • tests/unit/test_websocket_router.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/repo-architecture-review-n7rlg

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.

@github-actions
Copy link
Copy Markdown

FIPS Compatibility Check -- PASSED

Metric Count
Errors 0
Warnings 0
Info 3

Status: PASSED

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 30, 2026

⚠️ Deprecation Warning: The deny-licenses option is deprecated for possible removal in the next major release. For more information, see issue 997.

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@github-actions
Copy link
Copy Markdown

✅ Performance Regression Check

Status: PERFORMANCE OK

Metric Baseline (main) PR Branch Change
p95_ms 2.10 2.12 +1.1%

Threshold: +/-10% allowed regression

✅ Performance is within acceptable range.

Additional Metrics

Metric Baseline PR Change
p50_ms 1.82 1.82 📈 0.2%
p95_ms 2.10 2.12 📈 1.1%
p99_ms 2.22 2.27 📈 2.2%
mean_ms 1.30 1.31 📈 0.6%
min_ms 0.05 0.05 ➡️ 0.0%
max_ms 2.23 2.30 📈 3.2%
throughput_ops 770.66 765.78 📉 -0.6%
total_iterations 500.00 500.00 ➡️ 0.0%
avg_p95_all_benchmarks_ms 0.86 0.85 📉 -0.6%
avg_throughput_all_benchmarks_ops 1085148.40 1047693.01 📉 -3.5%
About Performance Regression Testing

This automated check compares p95_ms on this PR against the main branch baseline.

  • Regression Threshold: 10%
  • Warmup Iterations: 5
  • Benchmark Iterations: 50
  • Baseline Source: generated

To reproduce locally:

uv run --frozen  python scripts/benchmark.py --iterations 1000 

Copy link
Copy Markdown

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 implements a set of backend refactors to reduce duplication and improve end-to-end ingestion reliability: centralizing Redis client creation/pooling, completing the ingest→persist→enqueue pipeline (behind a default-off setting), consolidating Cloudflare Access JWT verification behavior across HTTP and WebSocket, and wiring the domain exception hierarchy into FastAPI.

Changes:

  • Centralized synchronous Redis client creation into core/redis.py (separate decoded vs raw pools) and updated queue/store components to use it.
  • Completed ingest pipeline wiring to persist/enqueue jobs when enqueue_enabled is set, and hardened worker task failure handling to mark jobs/batches failed instead of crashing/stalling.
  • Consolidated Cloudflare auth helpers (JWKS load locking + shared decode behavior) and registered a FastAPI exception handler for ProjectBaseError.

Reviewed changes

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

Show a summary per file
File Description
src/rag_processor/core/redis.py Adds shared decoded/raw Redis connection pools with shutdown cleanup.
src/rag_processor/queue/client.py Switches RQ client creation to use the shared raw Redis pool.
src/rag_processor/queue/redis_store.py Switches persistence layer to use the shared decoded Redis pool and adds batch deletion.
src/rag_processor/queue/jobs.py Adds async wrappers for Redis reads and hardens process_job_task failure handling.
src/rag_processor/api/ingest.py Wires persist+enqueue behind enqueue_enabled, adds rollback behavior on infra failures.
src/rag_processor/api/batch.py Offloads Redis reads from the event loop for batch/job status endpoints.
src/rag_processor/websocket/router.py Offloads Redis reads for WS subscription checks and event replay.
src/rag_processor/auth/cloudflare.py Consolidates JWKS loading/key resolution/decode helpers and shares leeway across auth paths.
src/rag_processor/core/exceptions.py Defines centralized domain exception hierarchy and HTTP status mapping.
src/rag_processor/main.py Wires app lifespan shutdown cleanup and registers ProjectBaseError exception handler.
tests/unit/test_core_redis.py Adds unit coverage for shared Redis pool behavior and pool shutdown reset.
tests/unit/test_jobs_async.py Adds tests for async wrappers and worker pipeline failure handling.
tests/unit/test_ingest.py Adds enqueue-gating tests and rollback behavior verification.
tests/unit/test_exception_handler.py Adds tests for domain-exception→HTTP mapping and FastAPI handler wiring.

Comment thread src/rag_processor/api/ingest.py Outdated
Comment on lines +221 to +223
try:
await asyncio.to_thread(get_redis_store().delete_batch, batch.batch_id)
except Exception: # noqa: BLE001 - rollback is best-effort
Comment thread src/rag_processor/websocket/router.py Outdated
# Verify batch exists and the caller owns it. Treat "not found" and
# "not authorized" identically to avoid leaking batch IDs.
batch, _ = get_batch_status(batch_id)
batch, _ = await asyncio.to_thread(get_batch_status, batch_id)
Responds to Copilot review on PR #61.

- enqueue_batch_jobs is now all-or-nothing: it tracks enqueued RQ jobs and,
  on any partial failure, cancels/deletes them and removes the batch's Redis
  state before re-raising. Prevents orphaned RQ jobs whose metadata would
  otherwise be deleted by the ingest rollback ("Job not found"). Extracted
  _rollback_enqueued_batch; added JOB_TIMEOUT_SECONDS constant.
- ingest _persist_and_enqueue rollback simplified to filesystem cleanup only,
  since enqueue_batch_jobs now owns its Redis/RQ rollback.
- websocket router uses the centralized get_batch_status_async wrapper instead
  of duplicating the asyncio.to_thread offload.

Tests: added transactional rollback + success coverage for enqueue_batch_jobs;
updated websocket/ingest tests accordingly. 448 passed.

https://claude.ai/code/session_01PA6dtgMhfzSe22VVtqBfxE
@github-actions
Copy link
Copy Markdown

✅ Performance Regression Check

Status: PERFORMANCE OK

Metric Baseline (main) PR Branch Change
p95_ms 2.22 2.13 -4.1%

Threshold: +/-10% allowed regression

✅ Performance is within acceptable range.

Additional Metrics

Metric Baseline PR Change
p50_ms 1.83 1.82 📉 -0.3%
p95_ms 2.22 2.13 📉 -4.1%
p99_ms 2.91 2.23 📉 -23.3%
mean_ms 1.35 1.30 📉 -3.7%
min_ms 0.05 0.05 ➡️ 0.0%
max_ms 4.17 2.25 📉 -46.0%
throughput_ops 739.55 767.92 📈 3.8%
total_iterations 500.00 500.00 ➡️ 0.0%
avg_p95_all_benchmarks_ms 0.89 0.86 📉 -3.6%
avg_throughput_all_benchmarks_ops 1040996.58 996425.59 📉 -4.3%
About Performance Regression Testing

This automated check compares p95_ms on this PR against the main branch baseline.

  • Regression Threshold: 10%
  • Warmup Iterations: 5
  • Benchmark Iterations: 50
  • Baseline Source: generated

To reproduce locally:

uv run --frozen  python scripts/benchmark.py --iterations 1000 

@sonarqubecloud
Copy link
Copy Markdown

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.

3 participants