Skip to content

fix: harden ingestion worker leases and address review follow-ups#937

Merged
cursor[bot] merged 8 commits into
mainfrom
cursor/ingestion-and-review-followups-0a3e
Jul 19, 2026
Merged

fix: harden ingestion worker leases and address review follow-ups#937
cursor[bot] merged 8 commits into
mainfrom
cursor/ingestion-and-review-followups-0a3e

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

  • Hardens administrator-only access across document, ingestion, and account APIs; adds signed-in favourites/preferences persistence; repairs mobile Safari bottom-composer spacing on Information pages; and fixes a pre-existing unit-test regression in the clinical dashboard merge-artifact guards.

Verification

  • npm run verify:cheap — local run on PR head: lint, typecheck, and 2892/2895 unit tests passed; 3 known failures remain in tests/pdf-extraction-budget.test.ts (Python/PDF fixture env); clinical-dashboard merge-artifact Safari reserve assertion fixed in this commit.
  • npm run check:production-readiness — passed locally for auth/privacy/admin-route changes.
  • npm run verify:ui — hosted Production UI gate on this PR head (UI-scoped paths include global-search-shell, detail pages, and DocumentViewer).

Risk and rollout

  • Risk: medium — touches Supabase migrations/RLS, administrator authorization, account persistence APIs, ingestion-worker auth, and mobile layout spacing; incorrect rollout could block uploads or expose admin affordances to non-administrators (API routes remain fail-closed).
  • Rollback: revert the PR commit and roll back the Supabase migrations in reverse order on the preview branch; account tables are additive and can remain without breaking reads.
  • Provider or production effects: requires applying new Supabase migrations and redeploying the ingestion-worker edge function; no change to answer-generation prompts or retrieval scoring.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy)
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative
  • Deployment classification/TGA SaMD impact was checked when clinical decision-support behavior changed

Notes

  • Resolves bottom layout spacing and transition issues on Information pages, removes the footer search composer from Information pages, restores the back button at desktop widths, and gates administrative upload-drawer assertions in tests to match production authorization.

- Pass workerId through complete/fail ingestion RPCs and skip counters
  when the lease was reclaimed by another worker.
- Generate embedding payloads before delete/insert and swap fields inside
  a single transaction to avoid partial enrichment gaps.
- Check private access before document readiness in DocumentViewer.summarize
  so signed-out users see the sign-in message.
- Return skill descriptions separately from validateSkillCatalog instead of
  mutating canonical catalog entries during validation.

Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
@supabase

supabase Bot commented Jul 19, 2026

Copy link
Copy Markdown

Updates to Preview Branch (cursor/ingestion-and-review-followups-0a3e) ↗︎

Deployments Status Updated
Database Sun, 19 Jul 2026 20:19:15 UTC
Services Sun, 19 Jul 2026 20:19:15 UTC
APIs Sun, 19 Jul 2026 20:19:15 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Sun, 19 Jul 2026 20:19:16 UTC
Migrations Sun, 19 Jul 2026 20:19:18 UTC
Seeding Sun, 19 Jul 2026 20:19:20 UTC
Edge Functions Sun, 19 Jul 2026 20:19:21 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@cursor[bot], you've reached your PR review limit, so we couldn't start this review.

Next review available in: 10 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 Plus

Run ID: 13385604-5da9-4620-84c5-00c137983707

📥 Commits

Reviewing files that changed from the base of the PR and between cc78491 and afad557.

📒 Files selected for processing (2)
  • src/components/DocumentViewer.tsx
  • src/lib/python-bin.ts
📝 Walkthrough

Walkthrough

The PR adds workflow policy validation, updates ingestion lease and embedding transaction handling, separates skill descriptions, restricts document management to administrators, refines summarization guards, and selects platform-appropriate Python executables.

Changes

PR policy hardening

Layer / File(s) Summary
Workflow guard and policy documentation
scripts/check-pr-policy-workflow.mjs, package.json, docs/process-hardening.md
Adds workflow-content checks and documents trusted github.workflow_sha checkout behavior.

Ingestion processing

Layer / File(s) Summary
Lease-aware ingestion and transactional embeddings
supabase/functions/ingestion-worker/index.ts
Adds concurrent embedding preparation, transactional replacement, and typed completion or retry RPC handling.
Lease-aware processing loop
supabase/functions/ingestion-worker/index.ts, tests/ingestion-edge-function-auth.test.ts
Tracks lease loss separately, updates responses and failure handling, and adds source assertions.

Skill catalog rendering

Layer / File(s) Summary
Description map and rendering
scripts/list-database-skills.mjs
Returns descriptions separately from canonical skill objects and uses the map when rendering summaries.

Document management access

Layer / File(s) Summary
Administrator-gated management actions
src/components/DocumentManagementActions.tsx, tests/account-access-model.test.ts
Requires authenticated administrator status for rename and delete actions and tests the source checks.

Document summarization controls

Layer / File(s) Summary
Summarization guards and action title
src/components/DocumentViewer.tsx
Prioritizes private-access errors, viewer readiness, and summary loading state.

Python executable selection

Layer / File(s) Summary
Platform-specific Python resolution
src/lib/python-bin.ts, src/lib/env.ts, src/lib/extractors/document.ts, tests/pdf-extractor.test.ts
Uses PYTHON_BIN when configured, otherwise selects platform-specific Python executables for extraction and tests.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Request as HTTP Request
  participant Worker as IngestionWorker
  participant Store as EmbeddingStore
  participant RPC as SupabaseRPC
  Request->>Worker: process claimed job
  Worker->>Store: generate embeddings and hashes
  Worker->>Store: replace fields in transaction
  Worker->>RPC: complete or fail/retry job
  RPC-->>Worker: return completion or lease-lost result
  Worker-->>Request: report processed, failed, and lease_lost counts
Loading

Possibly related PRs

  • BigSimmo/Database#716: Introduced the PR-policy workflows and related policy self-tests extended by this change.
  • BigSimmo/Database#884: Updated PR-policy checkout behavior validated by the new workflow guard.
  • BigSimmo/Database#932: Introduced the CI policy synchronization job validated by the new workflow guard.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% 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
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.
Title check ✅ Passed The title matches the main theme of hardening ingestion-worker lease handling and follow-up fixes.
Description check ✅ Passed The description follows the template and includes summary, verification, risk/rollback, clinical preflight, and notes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/ingestion-and-review-followups-0a3e

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

cursoragent and others added 2 commits July 19, 2026 19:23
- Use python3 by default on non-Windows when PYTHON_BIN is unset so PDF
  budget tests invoke the Python extractor instead of falling through to JS
- Extract completeIngestionJob/failOrRetryIngestionJob helpers and track
  lease_lost explicitly in the worker response instead of failed -= 1
- Align pdf-extractor test python bin resolution with production code

Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
@cursor
cursor Bot marked this pull request as ready for review July 19, 2026 19:40
- Gate DocumentManagementActions on isAdministratorUser for defense in depth
- Add check-pr-policy-workflow guard for pull_request_target hardening invariants
- Document trusted workflow_sha checkout in process-hardening notes
- Extend account-access model test to lock administrator client gate

Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>

@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: 4

🤖 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 `@scripts/check-pr-policy-workflow.mjs`:
- Around line 11-92: Replace the raw workflow-wide string checks in the
validation logic with YAML-aware inspection of the specific PR policy and
sync-pr-policy-body jobs, permissions, checkout steps, and script imports.
Validate executable checkout refs and credential settings rather than comments
or unrelated jobs; require workflow_sha, persist-credentials false, read-only
permissions, and trusted-base script imports. Expand forbidden checkout
validation to reject pull-request head ref variants, and ensure missing or
weakened settings fail the check.

In `@src/components/DocumentManagementActions.tsx`:
- Line 59: Revalidate authorization in both submit handlers in
DocumentManagementActions using the current canManage value before processing
submission. If permission is no longer available, prevent submission and close
or otherwise clear the active dialog mode so an already-open form cannot be
submitted after authentication or administrator status changes.

In `@src/lib/extractors/document.ts`:
- Around line 21-25: Update resolvePythonBin to consume the canonical parsed
PYTHON_BIN value from the existing environment configuration instead of
independently selecting python3 on non-Windows platforms. Ensure extraction and
worker/prerequisite checks use the same executable configuration; if the
environment schema is changed instead, update the corresponding prerequisites,
deployment documentation, and tests consistently.

In `@supabase/functions/ingestion-worker/index.ts`:
- Around line 218-260: Update processJob to conservatively handle completion
outcomes: treat null results and any ok === false reason other than lease_lost
as failures rather than returning "completed" or silently incrementing
processed, while preserving the lease_lost result. Add an early lease-ownership
validation before upsertDocumentSummary, upsertEmbeddingFields, and
markEnrichmentMetadata, or revalidate immediately before those writes, so a
worker that no longer owns the lease exits without performing redundant work.
🪄 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 Plus

Run ID: b2662162-3d7c-4699-a553-2a037a99deb3

📥 Commits

Reviewing files that changed from the base of the PR and between 27db15c and 41559d4.

📒 Files selected for processing (11)
  • docs/process-hardening.md
  • package.json
  • scripts/check-pr-policy-workflow.mjs
  • scripts/list-database-skills.mjs
  • src/components/DocumentManagementActions.tsx
  • src/components/DocumentViewer.tsx
  • src/lib/extractors/document.ts
  • supabase/functions/ingestion-worker/index.ts
  • tests/account-access-model.test.ts
  • tests/ingestion-edge-function-auth.test.ts
  • tests/pdf-extractor.test.ts

Comment thread scripts/check-pr-policy-workflow.mjs Outdated
Comment thread src/components/DocumentManagementActions.tsx
Comment thread src/lib/extractors/document.ts Outdated
Comment thread supabase/functions/ingestion-worker/index.ts
- Revalidate administrator access in DocumentManagementActions submit handlers
- Centralize resolvePythonBin for extraction, env defaults, and worker prerequisites
- Fail ingestion worker conservatively when complete_ingestion_job is ambiguous
- Parse PR policy workflow YAML by job/step instead of whole-file string matching

Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>

@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

🤖 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/python-bin.ts`:
- Around line 2-4: The resolved executable from resolvePythonBin must be trimmed
before return; use the trimmed nonblank explicit value while preserving the
existing platform defaults. In src/lib/python-bin.ts lines 2-4, update
resolvePythonBin accordingly; src/lib/env.ts line 211 requires no direct change
because it is corrected by this root-cause fix.
🪄 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 Plus

Run ID: e5dbd731-0207-41d2-8680-ea4888418894

📥 Commits

Reviewing files that changed from the base of the PR and between 41559d4 and 430ee1e.

📒 Files selected for processing (9)
  • scripts/check-pr-policy-workflow.mjs
  • src/components/DocumentManagementActions.tsx
  • src/lib/env.ts
  • src/lib/extractors/document.ts
  • src/lib/python-bin.ts
  • supabase/functions/ingestion-worker/index.ts
  • tests/account-access-model.test.ts
  • tests/ingestion-edge-function-auth.test.ts
  • tests/pdf-extractor.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/account-access-model.test.ts
  • src/components/DocumentManagementActions.tsx
  • scripts/check-pr-policy-workflow.mjs
  • supabase/functions/ingestion-worker/index.ts

Comment thread src/lib/python-bin.ts
cursoragent and others added 2 commits July 19, 2026 19:55
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
@cursor
cursor Bot enabled auto-merge (squash) July 19, 2026 20:18
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
@cursor
cursor Bot merged commit 096fbe9 into main Jul 19, 2026
18 checks passed
@cursor
cursor Bot deleted the cursor/ingestion-and-review-followups-0a3e branch July 19, 2026 20:26
cursor Bot pushed a commit that referenced this pull request Jul 19, 2026
Keep the header-edge-pad fix current with origin/main after #937.

Co-authored-by: BigSimmo <BigSimmo@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.

2 participants