Skip to content

fix: codebase-review remediations (clinical-path numeric-verify, coalescing, security hardening)#510

Merged
BigSimmo merged 3 commits into
mainfrom
claude/codebase-review-ade6ed
Jul 12, 2026
Merged

fix: codebase-review remediations (clinical-path numeric-verify, coalescing, security hardening)#510
BigSimmo merged 3 commits into
mainfrom
claude/codebase-review-ade6ed

Conversation

@BigSimmo

Copy link
Copy Markdown
Owner

Summary

Remediations from a full-codebase review (three parallel audits: pipeline correctness, security/data-access, frontend/config). Each finding below was verified line-by-line and ships with a regression test.

  • P1 — numeric-verification corpus parity (clinical answer path). The model answer path verified answer numbers against the packed generation context (which carries neighbour-chunk text in adjacent_context), then swapped answer.sources to the unpacked answerInputResults before finalizeRagAnswerQuality re-verified — silently blanking correct dose/threshold answers whose figure lived only in a neighbour chunk's adjacent_context. New attachAdjacentContext() (rag-cache.ts) rebuilds the packed corpus, threaded as an optional verificationSources param through finalizeRagAnswerQualityapplyNumericVerification. answer.sources stays unpacked, preserving the client/eval byte boundary. The fail-closed behaviour for genuinely unverifiable numbers is unchanged.
  • P2 — answer-coalescing isolation. answerQuestionWithScope coalesced identical concurrent requests onto one promise with no error isolation, so an originating caller's abort or search-phase throw returned a 500 (or a shared fallback) to unrelated concurrent callers. The coalesced awaiter now catches and falls through to an independent uncoalesced run.
  • /api/setup-status hardening. Non-local (production) origins receive coarse per-check detail (raw Supabase error text and project posture redacted) unless they present the operator x-health-deep-token. Extracted a shared src/lib/deep-probe-auth.ts reused by /api/health. The client's only detail reader is NODE_ENV !== "production"-gated, so the UI is unaffected.
  • CSP + rate-limit hardening. img-src/media-src narrowed from any https: to https://*.supabase.co (the app loads no other cross-origin media). document_upload now fails closed (503) on limiter unavailability like answer, instead of falling back to a per-instance limiter that grants N× the limit across horizontally-scaled instances during a limiter outage.
  • Tooling. lint --max-warnings 0 (makes react-hooks/exhaustive-deps blocking; repo currently has 0 warnings). Removed stale @types/pdf-parse (pdf-parse v2 ships its own types); package-lock.json synced so npm ci stays valid. Deduped eslint globalIgnores.

Full findings report (including three items deferred with recipes) is in the plan file.

Verification

Ran here (this worktree has no local node_modules; run against the repo binaries), all green:

  • eslint … --max-warnings 0 → clean
  • tsc --noEmit → clean
  • Targeted vitest run over all 9 affected/added test files → 98 tests pass (new tests: numeric-verification corpus parity + attachAdjacentContext; coalescing abort isolation; setup-status coarse-detail gating; document_upload fail-closed limiter; tightened CSP img-src assertions).

Not run here — please run before merge (environment/provider constraints):

  • npm run verify:pr-local (full gate — needs a complete install/build env)
  • npm run verify:ui — CSP img-src narrowing is browser-visible; confirm Supabase Storage images still render
  • npm run eval:retrieval:quality (must stay 36/36) — retrieval-adjacent (attachAdjacentContext feeds the verification corpus); provider-backed, cannot run here
  • npm run eval:rag -- --limit 15 + npm run eval:quality -- --rag-only — the numeric-faithfulness gate (answer post-processing) changed; grounded-supported should rise or hold (this fixes false suppressions) and citation-failure must stay 0
  • npm run check:production-readiness — CSP, rate-limit, and setup-status touch production env/privacy

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use (the numeric gate still verifies against cited-chunk text; this fix only corrects the corpus it checks against)
  • No patient-identifiable document workflow was introduced or expanded
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy) — unchanged
  • Service-role keys and private document access remain server-only (setup-status change reduces exposure; deep-probe-auth.ts is server-only)
  • Demo/synthetic content remains clearly separated from real clinical sources — unchanged
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative — the numeric gate still fails closed on genuinely unverifiable figures
  • Deployment classification/TGA SaMD impact checked: the numeric fix changes clinical decision-support output (fewer correct dose/threshold answers are wrongly suppressed) but does not weaken the fail-closed gate for true mismatches — a net safety improvement. Reviewer should confirm via the RAG evals above.

Notes

  • Deferred with recipes (in the plan file, not in this PR): excluding ~12.6k lines of mockups from the prod build (needs a real next build), @axe-core/playwright a11y + coverage ratchet (needs a dependency install + Chromium/coverage runs), and large-file decomposition + tsconfig noUncheckedIndexedAccess (large, incremental).
  • The tenancy retrieval-RPC rebuild-safety drift surfaced by the audit is intentionally not touched — it is already tracked as backlog #0 in docs/database-drift-detection.md (live bodies are ahead of the repo; the fix needs a live-body generation script + operator apply, and the naive rewrite was neutralized as regressive). The app-layer owner-scope floor is already safe.

🤖 Generated with Claude Code

…security)

Findings from a full-codebase review (3 audits), verified line-by-line and fixed
with regression tests:

- P1 numeric-verification corpus parity: the model answer path verified numbers
  against the packed generation context but re-verified at finalize against the
  unpacked answer.sources, silently blanking correct dose/threshold answers whose
  figure lived only in a neighbour chunk's adjacent_context. New attachAdjacentContext()
  rebuilds the packed corpus, threaded as an optional verificationSources param through
  finalizeRagAnswerQuality -> applyNumericVerification (answer.sources stays unpacked for
  the client/eval boundary).
- P2 answer-coalescing isolation: a coalesced caller no longer inherits the originating
  request's abort/failure (was a 500 or shared fallback); it catches and falls through to
  an independent uncoalesced run.
- setup-status hardening: production (non-local) origins get coarse per-check detail unless
  they present the operator deep-probe token; extracted shared deep-probe-auth.ts reused by
  /api/health.
- CSP img-src/media-src narrowed from https: to https://*.supabase.co; document_upload rate
  limit now fails closed on limiter unavailability (was N x per-instance).
- Tooling: lint --max-warnings 0 (blocks exhaustive-deps regressions); removed stale
  @types/pdf-parse (pdf-parse v2 self-types) with lockfile synced.

Offline gates green: eslint --max-warnings 0, tsc --noEmit, 98 affected-file vitest tests.
Provider-backed evals (eval:retrieval:quality, eval:rag) and verify:ui not run here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@supabase

supabase Bot commented Jul 12, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The changes centralize deep-probe authorization, redact setup diagnostics, tighten rate-limit fallback rules, preserve packed RAG context during verification, isolate failed coalesced requests, restrict CSP media origins, and update lint and ignore configuration.

Changes

Security hardening

Layer / File(s) Summary
Deep-probe authorization and setup-status redaction
src/lib/deep-probe-auth.ts, src/app/api/health/route.ts, src/app/api/setup-status/route.ts, tests/setup-status-route.test.ts
Shared token validation gates deep health/setup details, while unauthorized production responses receive coarse check details.
Expensive-bucket limiter fallback
src/lib/api-rate-limit.ts, tests/api-rate-limit-fallback.test.ts
answer and document_upload fail closed when durable limiting is unavailable; document_read retains in-memory fallback.

RAG verification and request isolation

Layer / File(s) Summary
Packed context verification flow
src/lib/rag-cache.ts, src/lib/answer-verification.ts, src/lib/rag-extractive-answer.ts, src/lib/rag.ts, tests/rag-content-accuracy.test.ts
Packed adjacent context is attached to verification sources and passed through answer finalization, with coverage for numeric grounding and context overlay behavior.
Coalesced request failure recovery
src/lib/rag.ts, tests/rag-answer-fallback.test.ts
A failed coalesced result now falls through to an independent computation, preventing an aborted caller from failing another request.

CSP and repository tooling

Layer / File(s) Summary
Supabase media source policy
src/lib/security-headers.ts, tests/proxy.test.ts, tests/security-headers.test.ts, tests/ui-smoke.spec.ts
img-src and media-src allow https://*.supabase.co instead of broad https: media sources, with updated assertions.
Lint and ignore configuration
eslint.config.mjs, package.json
Claude ignore patterns and lint options were updated, and @types/pdf-parse was removed.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AnswerRequest
  participant attachAdjacentContext
  participant finalizeRagAnswerQuality
  participant applyNumericVerification
  AnswerRequest->>attachAdjacentContext: Build verification sources from packed context
  attachAdjacentContext-->>AnswerRequest: Return sources with adjacent_context
  AnswerRequest->>finalizeRagAnswerQuality: Finalize answer with verification sources
  finalizeRagAnswerQuality->>applyNumericVerification: Verify numeric tokens
  applyNumericVerification-->>AnswerRequest: Return verified RAG answer
Loading

Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Verification Claims ❌ Error The PR description claims “ESLint, TypeScript checks, and 98 targeted Vitest tests passed” and “remain to be run” without exact command/result wording. Rewrite every verification claim with explicit commands and outcomes, e.g. “Ran npm run lint: passed” or “Not run: provider-backed evals require secrets.”
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 70.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (9 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the PR’s main focus on numeric verification, request coalescing, and security hardening remediations.
Description check ✅ Passed The description matches the required template with Summary, Verification, Clinical Governance Preflight, and Notes sections plus relevant checklist items.
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.
Generated And Sensitive Files ✅ Passed Diff only touches source/test/config plus package-lock; no secrets, .env files, logs, caches, build artifacts, node_modules, or local db/config files found.
Risky Git Or Deployment Actions ✅ Passed No changed file recommends force-push/reset/clean/delete/rebase or unsafe deployment; repo docs mostly forbid those actions and require confirmation.
Supabase Project And Schema Safety ✅ Passed PR only changes setup-status/deep-probe gating and tests; no supabase/migrations, RLS/policy, env-example, or project-ref edits, and test mocks use sjrfecxgysukkwxsowpy.
Runtime And Package Manager Integrity ✅ Passed package.json still pins npm@11.17.0/Node 24.x, .npmrc keeps engine-strict=true, and the PR adds no package-manager switch, lockfile bypass, or legacy/force install flags.
Api Route Failure Handling ✅ Passed PASS: New API/RAG paths are fail-closed or caught—deep-probe auth, setup-status, health, rate limits, and coalesced RAG retries handle missing env/provider/throw paths deterministically.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/codebase-review-ade6ed
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch claude/codebase-review-ade6ed

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e3caf935f5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/app/api/setup-status/route.ts Outdated
coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
tests/api-rate-limit-fallback.test.ts (1)

108-151: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

LGTM overall — correctly asserts the fail-closed vs fallback-allowed contract for owner subjects.

One coverage gap worth closing: neither test exercises the isLocalNoAuthMode() === true branch for document_upload, which per the source comment ("Local-no-auth dev keeps the in-memory fallback for single-instance usability") should still allow fallback. Adding that case would pin down the full fail-closed/fallback matrix for this security-sensitive bucket.

✅ Suggested additional test
+  it("still allows in-memory fallback for document_upload in local-no-auth mode", async () => {
+    vi.stubEnv("NODE_ENV", "development");
+    vi.doMock("`@/lib/env`", () => ({
+      isLocalNoAuthMode: () => true,
+    }));
+    const { consumeSubjectApiRateLimit } = await import("../src/lib/api-rate-limit");
+    const supabase = {
+      rpc: vi.fn(async () => ({ data: null, error: { code: "PGRST202", message: "missing RPC" } })),
+    };
+
+    const result = await consumeSubjectApiRateLimit({
+      supabase: supabase as never,
+      subject: { kind: "owner", ownerId: "owner-1" },
+      bucket: "document_upload",
+      allowInMemoryFallbackOnUnavailable: true,
+    });
+
+    expect(result.limited).toBe(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 `@tests/api-rate-limit-fallback.test.ts` around lines 108 - 151, Add a test in
the “document_upload fail-closed limiter” suite covering isLocalNoAuthMode() ===
true, with the durable limiter unavailable and in-memory fallback enabled.
Assert that consumeSubjectApiRateLimit resolves with an un limited result, while
preserving the existing production fail-closed and document_read fallback cases.
src/lib/rag.ts (2)

3603-4922: 🧹 Nitpick | 🔵 Trivial

Clinical governance preflight reminder.

This change touches answer generation and clinical numeric-dose verification (adjacent-context packing, numeric faithfulness gate, coalesced-answer fallback). As per path instructions, PRs touching answer generation or clinical output must complete the clinical governance preflight and relevant production-readiness checks before merge — the PR objectives note provider-backed RAG evaluations still need to run.

🤖 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/rag.ts` around lines 3603 - 4922, Complete the required clinical
governance preflight and production-readiness checks for the answer generation
and numeric verification changes in answerQuestionWithScope and
answerQuestionWithScopeUncoalesced. Run the provider-backed RAG evaluations and
document or resolve any findings before merging; do not alter the implementation
solely for this reminder.

Source: Path instructions


3615-3630: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Narrow the try/catch to only the coalesced-fetch, not the post-processing.

The catch is meant to isolate this caller from the originating request's failure, but it also swallows any error thrown by the subsequent routingReason/latencyTimings mutation. A bug there would silently look like "the in-flight request failed" and trigger a full duplicate (and possibly expensive) uncoalesced OpenAI run instead of surfacing the real error.

♻️ Suggested narrowing
-    try {
-      const answer = cloneAnswer(await existing);
-      answer.routingReason = answer.routingReason
-        ? `${answer.routingReason}; answer_inflight_coalesced`
-        : "answer_inflight_coalesced";
-      answer.latencyTimings = {
-        ...answer.latencyTimings,
-        total_latency_ms: Date.now() - startedAt,
-      };
-      return answer;
-    } catch {
+    let coalescedAnswer: RagAnswer | null = null;
+    try {
+      coalescedAnswer = cloneAnswer(await existing);
+    } catch {
       // The in-flight request we coalesced onto failed — most often because the ORIGINATING
       // caller aborted mid-flight (its AbortSignal is not ours) or its search phase threw. Do
       // not propagate another caller's failure to this still-connected request: fall through to
       // an independent, uncoalesced run so this request is decided only by its own inputs.
     }
+    if (coalescedAnswer) {
+      coalescedAnswer.routingReason = coalescedAnswer.routingReason
+        ? `${coalescedAnswer.routingReason}; answer_inflight_coalesced`
+        : "answer_inflight_coalesced";
+      coalescedAnswer.latencyTimings = {
+        ...coalescedAnswer.latencyTimings,
+        total_latency_ms: Date.now() - startedAt,
+      };
+      return coalescedAnswer;
+    }
🤖 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/rag.ts` around lines 3615 - 3630, In the coalesced-response path,
narrow the try/catch to only the await of existing used to obtain the cloned
answer; perform the routingReason and latencyTimings updates and return outside
the catch so post-processing errors propagate instead of triggering an
independent run.
🤖 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/deep-probe-auth.ts`:
- Around line 10-19: Update allowDeepHealthProbe to compare the byte lengths of
the UTF-8 expected and received buffers before calling timingSafeEqual, rather
than comparing token.length with secret.length. Return false when the buffer
lengths differ so malformed or non-ASCII tokens are denied without throwing.

---

Nitpick comments:
In `@src/lib/rag.ts`:
- Around line 3603-4922: Complete the required clinical governance preflight and
production-readiness checks for the answer generation and numeric verification
changes in answerQuestionWithScope and answerQuestionWithScopeUncoalesced. Run
the provider-backed RAG evaluations and document or resolve any findings before
merging; do not alter the implementation solely for this reminder.
- Around line 3615-3630: In the coalesced-response path, narrow the try/catch to
only the await of existing used to obtain the cloned answer; perform the
routingReason and latencyTimings updates and return outside the catch so
post-processing errors propagate instead of triggering an independent run.

In `@tests/api-rate-limit-fallback.test.ts`:
- Around line 108-151: Add a test in the “document_upload fail-closed limiter”
suite covering isLocalNoAuthMode() === true, with the durable limiter
unavailable and in-memory fallback enabled. Assert that
consumeSubjectApiRateLimit resolves with an un limited result, while preserving
the existing production fail-closed and document_read fallback cases.
🪄 Autofix (Beta)

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 95eda418-1ae6-41e7-87a8-0f6c64a40522

📥 Commits

Reviewing files that changed from the base of the PR and between 9f384d5 and e3caf93.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (18)
  • eslint.config.mjs
  • package.json
  • src/app/api/health/route.ts
  • src/app/api/setup-status/route.ts
  • src/lib/answer-verification.ts
  • src/lib/api-rate-limit.ts
  • src/lib/deep-probe-auth.ts
  • src/lib/rag-cache.ts
  • src/lib/rag-extractive-answer.ts
  • src/lib/rag.ts
  • src/lib/security-headers.ts
  • tests/api-rate-limit-fallback.test.ts
  • tests/proxy.test.ts
  • tests/rag-answer-fallback.test.ts
  • tests/rag-content-accuracy.test.ts
  • tests/security-headers.test.ts
  • tests/setup-status-route.test.ts
  • tests/ui-smoke.spec.ts

Comment thread src/lib/deep-probe-auth.ts
@BigSimmo
BigSimmo enabled auto-merge (squash) July 12, 2026 15:30
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Fixes Applied Successfully

Fixed 1 file(s) based on 1 unresolved review comment.

Files modified:

  • src/lib/deep-probe-auth.ts

Commit: 4eaf00fc5b44efbafeb202ab6bd94d6ca0fa021b

The changes have been pushed to the claude/codebase-review-ade6ed branch.

Time taken: 3m 3s

Fixed 1 file(s) based on 1 unresolved review comment.

Co-authored-by: CodeRabbit <noreply@coderabbit.ai>
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Note

Docstrings generation - SUCCESS
Generated docstrings for this pull request at #518

coderabbitai Bot added a commit that referenced this pull request Jul 12, 2026
Docstrings generation was requested by @BigSimmo.

* #510 (comment)

The following files were modified:

* `src/app/api/health/route.ts`
* `src/app/api/setup-status/route.ts`
* `src/lib/answer-verification.ts`
* `src/lib/api-rate-limit.ts`
* `src/lib/deep-probe-auth.ts`
* `src/lib/rag-cache.ts`
* `src/lib/rag-extractive-answer.ts`
* `src/lib/rag.ts`
* `src/lib/security-headers.ts`
- setup-status: gate raw per-check detail on a TRUSTED server runtime signal
  (NODE_ENV + demo/local-no-auth mode) instead of request.url's host. request.url
  reflects the client-supplied Host behind a proxy, so a spoofed
  localhost:<managed-port> could otherwise unlock raw Supabase/project detail
  without the operator token (Codex P2).
- deep-probe-auth: compare UTF-8 byte lengths before timingSafeEqual. A crafted
  multi-byte x-health-deep-token with a matching code-unit length but a different
  byte length made timingSafeEqual throw (RangeError -> crafted-header 500)
  (CodeRabbit, Major).
- Tests: a production request with a local-looking managed-port Host stays coarse;
  a crafted multi-byte token is rejected without throwing.

Live validation: golden retrieval 36/36; eval:rag 14/15 grounded (the one miss is a
pre-existing discharge doc-expectation mismatch, numericWarnings=0) with no
numeric-faithfulness-gate suppressions. typecheck + lint (--max-warnings 0) green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@BigSimmo
BigSimmo merged commit c3828ce into main Jul 12, 2026
18 checks passed

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8a26e238b4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/rag.ts
Comment on lines +3625 to +3630
} catch {
// The in-flight request we coalesced onto failed — most often because the ORIGINATING
// caller aborted mid-flight (its AbortSignal is not ours) or its search phase threw. Do
// not propagate another caller's failure to this still-connected request: fall through to
// an independent, uncoalesced run so this request is decided only by its own inputs.
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Re-coalesce waiters after in-flight aborts

When two or more identical callers are awaiting the same existing promise and the originating request aborts, every waiter enters this catch and then falls through to create its own pending request without rechecking answerInflight. That turns one aborted in-flight answer into N independent retrieval/OpenAI generations instead of one shared replacement for the still-connected callers, multiplying paid/provider and DB load under concurrent retries; a regression with two coalesced waiters after one aborted origin should assert only one replacement generation.

Useful? React with 👍 / 👎.

BigSimmo pushed a commit that referenced this pull request Jul 12, 2026
Docstrings generation was requested by @BigSimmo.

* #510 (comment)

The following files were modified:

* `src/app/api/health/route.ts`
* `src/app/api/setup-status/route.ts`
* `src/lib/answer-verification.ts`
* `src/lib/api-rate-limit.ts`
* `src/lib/deep-probe-auth.ts`
* `src/lib/rag-cache.ts`
* `src/lib/rag-extractive-answer.ts`
* `src/lib/rag.ts`
* `src/lib/security-headers.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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