-
Notifications
You must be signed in to change notification settings - Fork 3
Bulk Upsert (note that the first part was accidentally already merged in main before) #187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
34c3f1d
prevent duplicate entries in payload from crashing the entire upsert
NumericalAdvantage 9406882
pass text client headers properly, use pk to get model fields
NumericalAdvantage fd83435
radis/reports/api/viewsets.py
NumericalAdvantage 8f80037
fix JSON serialization
NumericalAdvantage 04c20ce
remove unused import
NumericalAdvantage 4fe5c38
Make bulk upsert indexing async and enforce group scope
NumericalAdvantage b36e259
Configure optional CA bundle for LLM worker
NumericalAdvantage 1d12394
Harden bulk indexing and cleanup bulk upsert
NumericalAdvantage 743812c
Fix lint in pgsearch indexing
NumericalAdvantage 2d5c6d2
Fix pyright type for bulk index enqueue
NumericalAdvantage f4f0432
Drop unrelated SSL/CA-bundle and YAML-anchor changes
NumericalAdvantage File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import logging | ||
|
|
||
| from procrastinate.contrib.django import app | ||
| from procrastinate.types import JSONValue | ||
|
|
||
| from .utils.indexing import bulk_upsert_report_search_vectors | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @app.task | ||
| def bulk_index_reports(report_ids: list[int]) -> None: | ||
| if not report_ids: | ||
| return | ||
| logger.info("Indexing %s reports in bulk.", len(report_ids)) | ||
| bulk_upsert_report_search_vectors(report_ids) | ||
|
|
||
|
|
||
| def enqueue_bulk_index_reports(report_ids: list[int]) -> int | None: | ||
| if not report_ids: | ||
| return None | ||
| try: | ||
| payload: list[JSONValue] = [int(report_id) for report_id in report_ids] | ||
| except (TypeError, ValueError) as exc: | ||
| logger.error("Invalid report_id in bulk index request: %s", exc) | ||
| return None | ||
| return app.configure_task( | ||
| "radis.pgsearch.tasks.bulk_index_reports", | ||
| allow_unknown=False, | ||
| ).defer(report_ids=payload) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import pytest | ||
|
|
||
| from radis.pgsearch.models import ReportSearchVector | ||
| from radis.pgsearch.utils.indexing import bulk_upsert_report_search_vectors | ||
| from radis.reports.models import Language, Report | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_bulk_index_matches_signal_vector() -> None: | ||
| language = Language.objects.create(code="en") | ||
| report = Report.objects.create( | ||
| document_id="DOC-INDEX", | ||
| pacs_aet="PACS", | ||
| pacs_name="PACS", | ||
| pacs_link="", | ||
| patient_id="P1", | ||
| patient_birth_date="1980-01-01", | ||
| patient_sex="M", | ||
| study_description="Study", | ||
| study_datetime="2024-01-01T00:00:00Z", | ||
| study_instance_uid="1.2.3.4", | ||
| accession_number="ACC1", | ||
| body="Findings: No acute abnormality.", | ||
| language=language, | ||
| ) | ||
|
|
||
| signal_vector = ReportSearchVector.objects.get(report=report).search_vector | ||
| ReportSearchVector.objects.filter(report=report).delete() | ||
|
|
||
| bulk_upsert_report_search_vectors([report.pk]) | ||
| bulk_vector = ReportSearchVector.objects.get(report=report).search_vector | ||
|
|
||
| assert signal_vector == bulk_vector |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from collections.abc import Iterable | ||
|
|
||
| from django.conf import settings | ||
| from django.db import connection | ||
|
|
||
| from radis.reports.models import Report | ||
|
|
||
| from ..models import ReportSearchVector | ||
| from .language_utils import code_to_language | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _chunked(items: list[int], size: int) -> Iterable[list[int]]: | ||
| for index in range(0, len(items), size): | ||
| yield items[index : index + size] | ||
|
|
||
|
|
||
| def bulk_upsert_report_search_vectors( | ||
| report_ids: Iterable[int], | ||
| chunk_size: int | None = None, | ||
| ) -> None: | ||
| ids = sorted({int(report_id) for report_id in report_ids if report_id is not None}) | ||
| if not ids: | ||
| return | ||
| resolved_chunk_size = ( | ||
| settings.PGSEARCH_BULK_INDEX_CHUNK_SIZE if chunk_size is None else chunk_size | ||
| ) | ||
|
|
||
| for chunk in _chunked(ids, resolved_chunk_size): | ||
| reports = ( | ||
| Report.objects.filter(id__in=chunk) | ||
| .select_related("language") | ||
| .only("id", "language__code") | ||
| ) | ||
| report_ids_found: set[int] = set() | ||
| config_to_ids: dict[str, list[int]] = {} | ||
| config_cache: dict[str, str] = {} | ||
| for report in reports: | ||
| report_ids_found.add(report.pk) | ||
| language_code = report.language.code | ||
| config = config_cache.get(language_code) | ||
| if config is None: | ||
| config = code_to_language(language_code) | ||
| config_cache[language_code] = config | ||
| config_to_ids.setdefault(config, []).append(report.pk) | ||
| missing_ids = set(chunk) - report_ids_found | ||
| if missing_ids: | ||
| logger.warning( | ||
| "Skipping %s missing reports during bulk index (ids=%s).", | ||
| len(missing_ids), | ||
| sorted(missing_ids)[:10], | ||
| ) | ||
|
|
||
| for config, config_ids in config_to_ids.items(): | ||
| ReportSearchVector.objects.bulk_create( | ||
| [ReportSearchVector(report_id=report_id) for report_id in config_ids], | ||
| ignore_conflicts=True, | ||
| batch_size=settings.PGSEARCH_BULK_INSERT_BATCH_SIZE, | ||
| ) | ||
|
|
||
| with connection.cursor() as cursor: | ||
| cursor.execute( | ||
| """ | ||
| UPDATE pgsearch_reportsearchvector v | ||
| SET search_vector = to_tsvector(%s::regconfig, r.body) | ||
| FROM reports_report r | ||
| WHERE v.report_id = r.id AND r.id = ANY(%s) | ||
| """, | ||
| [config, config_ids], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don’t drop valid IDs when one entry is invalid.
Right now a single bad
report_idprevents the entire batch from enqueuing, which can leave valid reports unindexed. Consider per-item validation (skip/log invalids) or explicitly raise so the caller can retry.✅ Suggested fix (skip invalid IDs, keep valid ones)
def enqueue_bulk_index_reports(report_ids: list[int]) -> int | None: if not report_ids: return None - try: - payload: list[int] = [int(report_id) for report_id in report_ids] - except (TypeError, ValueError) as exc: - logger.error("Invalid report_id in bulk index request: %s", exc) - return None + payload: list[int] = [] + for report_id in report_ids: + try: + payload.append(int(report_id)) + except (TypeError, ValueError): + logger.exception( + "Invalid report_id in bulk index request: %r", + report_id, + ) + if not payload: + return None return app.configure_task( "radis.pgsearch.tasks.bulk_index_reports", allow_unknown=False, ).defer(report_ids=payload)🧰 Tools
🪛 Ruff (0.14.14)
24-24: Use
logging.exceptioninstead oflogging.errorReplace with
exception(TRY400)
🤖 Prompt for AI Agents