diff --git a/.claude/conventions/celery.md b/.claude/conventions/celery.md index e3340ca46..27d787daa 100644 --- a/.claude/conventions/celery.md +++ b/.claude/conventions/celery.md @@ -53,7 +53,7 @@ the bands already in use (see the `job_execution.py` module docstring): |---|---|---| | `9` | `default` | User-blocking, interactive — LLM call / chain / response jobs | | `9` | `evaluations` | Fast evaluation chunk/aggregate (top band of this queue; new eval tasks pick a lower band) | -| `2` | `default` | Default — doctransform, collections, assessment | +| `2` | `default` | Default — collections, assessment | | `2` | `evaluations` | STT evaluation (batch submission, metric computation) and TTS evaluation (batch submission, sync generation, result processing) — below fast eval | | `1` | `default` | Notifications and other fire-and-forget background work | diff --git a/.claude/conventions/service.md b/.claude/conventions/service.md index 8208704b6..d29a9d4a0 100644 --- a/.claude/conventions/service.md +++ b/.claude/conventions/service.md @@ -1,7 +1,7 @@ # Service conventions (`app/services/`) Authoritative conventions for business-logic services in kaapi-backend. Services live in -`app/services//` (auth, collections, doctransform, llm, evaluations, ...). +`app/services//` (auth, collections, documents, llm, evaluations, ...). Services are where orchestration happens — they call CRUD for DB work and call external HTTP libraries for third-party APIs. diff --git a/.env.example b/.env.example index bfc35bfe2..d002b3272 100644 --- a/.env.example +++ b/.env.example @@ -29,7 +29,6 @@ PENDING_JOB_MONITOR_INTERVAL_MINUTES=5 PENDING_RECENT_GRACE_MINUTES=3 LLM_PENDING_THRESHOLD_MINUTES=30 COLLECTION_PENDING_THRESHOLD_MINUTES=30 -DOC_TRANSFORMATION_PENDING_THRESHOLD_MINUTES=30 PENDING_JOB_QUERY_TIMEOUT_MS=1000 # Rate limits (requests per minute per organization; over-limit calls get 429) @@ -110,9 +109,6 @@ TTS_QUEUED_STALE_SECONDS=86400 CALLBACK_CONNECT_TIMEOUT = 3 CALLBACK_READ_TIMEOUT = 10 -# require as a env if you want to use doc transformation -OPENAI_API_KEY="" - # Platform-owned Anthropic key for AI-assisted prompt improvement. # Shared across all orgs/projects so the feature works without per-project credentials. ANTHROPIC_API_KEY="" diff --git a/.env.test.example b/.env.test.example index 9b42d15d9..b9f41a890 100644 --- a/.env.test.example +++ b/.env.test.example @@ -33,7 +33,5 @@ AWS_S3_BUCKET_PREFIX="bucket-prefix-name" CALLBACK_CONNECT_TIMEOUT = 3 CALLBACK_READ_TIMEOUT = 10 -OPENAI_API_KEY="" - KAAPI_GUARDRAILS_AUTH="" KAAPI_GUARDRAILS_URL="" diff --git a/CLAUDE.md b/CLAUDE.md index 6aff891e0..cdd7f8812 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,6 @@ The backend follows a layered architecture located in `backend/app/`: - Database connection and session management - Security (JWT, password hashing, API keys) - Cloud storage (`cloud/storage.py`) - - Document transformation (`doctransform/`) - Fine-tuning utilities (`finetune/`) - Langfuse observability integration (`langfuse/`) - Exception handlers and middleware diff --git a/backend/app/alembic/versions/096_drop_doc_transformation_job_table.py b/backend/app/alembic/versions/096_drop_doc_transformation_job_table.py new file mode 100644 index 000000000..55fd63340 --- /dev/null +++ b/backend/app/alembic/versions/096_drop_doc_transformation_job_table.py @@ -0,0 +1,113 @@ +"""drop doc_transformation_job + +Revision ID: 096 +Revises: 095 +Create Date: 2026-12-04 00:00:00.000000 + +The Document transformation module was removed, so nothing reads or writes this +table any more. Rows are lost on upgrade; downgrade restores the schema as it stood +at 095 (an empty table) so older code can boot, not the data. + +document.source_document_id is kept: transformed documents that already exist are +still ordinary documents and remain listable. +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision = "096" +down_revision = "095" +branch_labels = None +depends_on = None + + +def upgrade(): + op.drop_table("doc_transformation_job") + op.execute("DROP TYPE IF EXISTS transformationstatus") + + +def downgrade(): + transformation_status = postgresql.ENUM( + "PENDING", "PROCESSING", "COMPLETED", "FAILED", name="transformationstatus" + ) + + op.create_table( + "doc_transformation_job", + sa.Column( + "id", + sa.Uuid(), + nullable=False, + comment="Unique identifier for the transformation job", + ), + sa.Column( + "source_document_id", + sa.Uuid(), + nullable=False, + comment="Reference to the source document being transformed", + ), + sa.Column( + "transformed_document_id", + sa.Uuid(), + nullable=True, + comment="Reference to the resulting transformed document", + ), + sa.Column( + "status", + transformation_status, + nullable=False, + comment="Current status (PENDING, PROCESSING, COMPLETED, FAILED)", + ), + sa.Column( + "error_message", + sa.String(), + nullable=True, + comment="Error message if transformation failed", + ), + sa.Column( + "inserted_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the job was created", + ), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the job was last updated", + ), + sa.Column( + "task_id", + sa.String(), + nullable=True, + comment="Celery task ID for async processing", + ), + sa.Column( + "trace_id", + sa.String(), + nullable=True, + comment="Tracing ID for correlating logs and traces", + ), + sa.ForeignKeyConstraint( + ["source_document_id"], ["document.id"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint( + ["transformed_document_id"], ["document.id"], ondelete="CASCADE" + ), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + "ix_doc_transformation_job_source_document_id", + "doc_transformation_job", + ["source_document_id"], + ) + op.create_index( + "ix_doc_transformation_job_transformed_document_id", + "doc_transformation_job", + ["transformed_document_id"], + ) + op.create_index( + "ix_doc_transformation_job_status_inserted_at", + "doc_transformation_job", + ["status", "inserted_at"], + ) diff --git a/backend/app/api/docs/documents/job_info.md b/backend/app/api/docs/documents/job_info.md deleted file mode 100644 index 387623bd4..000000000 --- a/backend/app/api/docs/documents/job_info.md +++ /dev/null @@ -1,3 +0,0 @@ -Get the status and details of a document transformation job. - -If you set the ``include_url`` parameter to true, a signed URL will be included in the response, which is a clickable link to access the transformed document if the job has been successful. If you don't set it to true, the URL will not be included in the response. diff --git a/backend/app/api/docs/documents/job_list.md b/backend/app/api/docs/documents/job_list.md deleted file mode 100644 index 1b0a1e44a..000000000 --- a/backend/app/api/docs/documents/job_list.md +++ /dev/null @@ -1,3 +0,0 @@ -Get the status and details of multiple document transformation jobs by IDs. - -If you set the ``include_url`` parameter to true, a signed URL will be included in the response, which is a clickable link to access the transformed document for successful jobs. If you don't set it to true, the URL will not be included in the response. diff --git a/backend/app/api/docs/documents/permanent_delete.md b/backend/app/api/docs/documents/permanent_delete.md index 483c80b8f..45463d403 100644 --- a/backend/app/api/docs/documents/permanent_delete.md +++ b/backend/app/api/docs/documents/permanent_delete.md @@ -1,7 +1,7 @@ Permanently delete a document. The file is removed from cloud storage (e.g., S3) and the database record is deleted. This cannot be undone. Records -that depend on the document, such as its transformed documents, transformation jobs, fine-tuning jobs and model +that depend on the document, such as its transformed documents, fine-tuning jobs and model evaluations, are deleted along with it. Works on both active and soft-deleted documents. Collections and knowledge bases that contain this document are not diff --git a/backend/app/api/docs/documents/upload.md b/backend/app/api/docs/documents/upload.md index 7d5855654..d5fbc6713 100644 --- a/backend/app/api/docs/documents/upload.md +++ b/backend/app/api/docs/documents/upload.md @@ -1,18 +1,3 @@ -Upload a document to Kaapi and optionally transform it as well. +Upload a document to Kaapi. -- If only a file is provided, the document will be uploaded and stored, and its ID will be returned. The maximum file size allowed for upload is 25 MB. -- If a target format is specified, a transformation job will also be created to transform document into target format in the background. The response will include both the uploaded document details and information about the transformation job. -- If a callback URL is provided, you will receive a notification at that URL once the document transformation job is completed. - -### Supported Conversions: - -The following (source_format → target_format) transformations are supported for now: - -- pdf → markdown - - zerox - -### Transformers: - -Available transformer names and their implementations, default transformer is zerox for now: - -- `zerox` +The document is uploaded and stored, and its ID is returned along with a signed URL to access it. The maximum file size allowed for upload is 25 MB. diff --git a/backend/app/api/docs/documents/v2/register.md b/backend/app/api/docs/documents/v2/register.md index 30239c8be..0b01ba803 100644 --- a/backend/app/api/docs/documents/v2/register.md +++ b/backend/app/api/docs/documents/v2/register.md @@ -4,4 +4,4 @@ Final step of the v2 upload flow, and it takes no request body. The uploaded obj Errors: `400` if nothing was uploaded for that `document_id` (the upload never happened or the URL lapsed); `409` if the `document_id` was already registered — open a new upload session in that case. -The 25 MB cap is enforced by storage while the file uploads, so an oversized file never reaches this step. Document transformation is not available on v2. Use `POST /api/v1/documents` if you need a `target_format` conversion. +The 25 MB cap is enforced by storage while the file uploads, so an oversized file never reaches this step. diff --git a/backend/app/api/main.py b/backend/app/api/main.py index a6e422cbf..0062448dc 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -12,7 +12,6 @@ credentials, cron, decision, - doc_transformation_job, documents, evaluations, features, @@ -55,7 +54,6 @@ api_router.include_router(credentials.router) api_router.include_router(cron.router) api_router.include_router(decision.router) -api_router.include_router(doc_transformation_job.router) api_router.include_router(documents.router) api_router.include_router(duplicate_detection.router) api_router.include_router(evaluations.router) diff --git a/backend/app/api/routes/doc_transformation_job.py b/backend/app/api/routes/doc_transformation_job.py deleted file mode 100644 index 367a2745e..000000000 --- a/backend/app/api/routes/doc_transformation_job.py +++ /dev/null @@ -1,115 +0,0 @@ -from uuid import UUID -import logging - -from fastapi import APIRouter, Depends, Query, Path - -from app.api.deps import AuthContextDep, SessionDep -from app.api.permissions import Permission, require_permission -from app.crud import DocTransformationJobCrud, DocumentCrud -from app.models import ( - DocTransformationJobPublic, - DocTransformationJobsPublic, -) -from app.utils import APIResponse, load_description -from app.services.documents.helpers import build_job_schema, build_job_schemas -from app.core.cloud import get_cloud_storage - - -logger = logging.getLogger(__name__) -router = APIRouter(prefix="/documents/transformation", tags=["Documents"]) - - -@router.get( - "/{job_id}", - description=load_description("documents/job_info.md"), - response_model=APIResponse[DocTransformationJobPublic], - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_transformation_job( - session: SessionDep, - current_user: AuthContextDep, - job_id: UUID = Path(..., description="Transformation job ID"), - include_url: bool = Query( - False, description="Include a signed URL for the transformed document" - ), - download: bool = Query( - False, - description=( - "When true the signed URL forces a download under the document's " - "original filename; when false it opens inline in the browser" - ), - ), -): - job_crud = DocTransformationJobCrud(session, current_user.project_.id) - doc_crud = DocumentCrud(session, current_user.project_.id) - - job = job_crud.read_one(job_id) - storage = ( - get_cloud_storage(session=session, project_id=current_user.project_.id) - if include_url - else None - ) - - job_schema = build_job_schema( - job=job, - doc_crud=doc_crud, - include_url=include_url, - storage=storage, - download=download, - ) - return APIResponse.success_response(job_schema) - - -@router.get( - "", - description=load_description("documents/job_list.md"), - response_model=APIResponse[DocTransformationJobsPublic], - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_multiple_transformation_jobs( - session: SessionDep, - current_user: AuthContextDep, - job_ids: list[UUID] = Query( - ..., - description="List of transformation job IDs", - min_items=1, - max_items=100, - ), - include_url: bool = Query( - False, description="Include a signed URL for each transformed document" - ), - download: bool = Query( - False, - description=( - "When true the signed URL forces a download under the document's " - "original filename; when false it opens inline in the browser" - ), - ), -): - job_crud = DocTransformationJobCrud(session, project_id=current_user.project_.id) - doc_crud = DocumentCrud(session, project_id=current_user.project_.id) - - jobs = job_crud.read_each(set(job_ids)) - jobs_found_ids = {job.id for job in jobs} - jobs_not_found = set(job_ids) - jobs_found_ids - - storage = ( - get_cloud_storage(session=session, project_id=current_user.project_.id) - if include_url - else None - ) - - job_schemas = build_job_schemas( - jobs=jobs, - doc_crud=doc_crud, - include_url=include_url, - storage=storage, - download=download, - ) - - return APIResponse.success_response( - DocTransformationJobsPublic( - jobs=job_schemas, - jobs_not_found=list(jobs_not_found), - ) - ) diff --git a/backend/app/api/routes/documents/document.py b/backend/app/api/routes/documents/document.py index 50b7ac00f..70c999771 100644 --- a/backend/app/api/routes/documents/document.py +++ b/backend/app/api/routes/documents/document.py @@ -7,7 +7,6 @@ APIRouter, Depends, File, - Form, Query, UploadFile, ) @@ -23,8 +22,6 @@ TransformedDocumentPublic, DocumentUploadResponse, Message, - TransformationJobInfo, - DocTransformationJobPublic, ) from app.core.cloud import get_cloud_storage from app.services.documents.constants import ( @@ -33,7 +30,6 @@ ) from app.services.documents.helpers import ( calculate_file_size, - schedule_transformation, validate_upload, build_document_schema, build_document_schemas, @@ -41,31 +37,11 @@ from app.utils import ( APIResponse, load_description, - validate_callback_url, ) logger = logging.getLogger(__name__) router = APIRouter(prefix="/documents", tags=["Documents"]) -doctransformation_callback_router = APIRouter() - - -@doctransformation_callback_router.post( - "{$callback_url}", - name="doctransformation_callback", -) -def doctransformation_callback_notification( - body: APIResponse[DocTransformationJobPublic], -): - """ - Callback endpoint specification for document transformation. - - The callback will receive: - - On success: APIResponse with success=True and data containing DocTransformationJobPublic - - On failure: APIResponse with success=False and error message - - metadata field will always be included if provided in the request - """ - ... @router.get( @@ -114,36 +90,17 @@ def list_docs( "", description=load_description("documents/upload.md"), response_model=APIResponse[DocumentUploadResponse], - callbacks=doctransformation_callback_router.routes, dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], ) async def upload_doc( session: SessionDep, current_user: AuthContextDep, src: UploadFile = File(...), - target_format: str - | None = Form( - None, - description="Desired output format for the uploaded document", - ), - transformer: str - | None = Form( - None, description="Name of the transformer to apply when converting." - ), - callback_url: str - | None = Form(None, description="URL to call to report doc transformation status"), ) -> APIResponse[DocumentUploadResponse]: - if callback_url: - validate_callback_url(callback_url) - if src.filename is None: raise HTTPException(status_code=400, detail="Uploaded file has no filename") - source_format, actual_transformer = validate_upload( - src=src, - target_format=target_format, - transformer=transformer, - ) + validate_upload(src=src) file_size_kb = calculate_file_size(src) file_size_mb = file_size_kb / 1024 @@ -173,16 +130,6 @@ async def upload_doc( ) source_document = crud.update(document) - job_info: TransformationJobInfo | None = schedule_transformation( - session=session, - project_id=current_user.project_.id, - source_format=source_format, - target_format=target_format, - actual_transformer=actual_transformer, - source_document_id=source_document.id, - callback_url=callback_url, - ) - document_schema = DocumentPublic.model_validate( source_document, from_attributes=True ) @@ -190,10 +137,7 @@ async def upload_doc( source_document.object_store_url ) - response = DocumentUploadResponse( - **document_schema.model_dump(), - transformation_job=job_info, - ) + response = DocumentUploadResponse(**document_schema.model_dump()) return APIResponse[DocumentUploadResponse].success_response(response) diff --git a/backend/app/celery/tasks/job_execution.py b/backend/app/celery/tasks/job_execution.py index fae7054b5..4e38ceb84 100644 --- a/backend/app/celery/tasks/job_execution.py +++ b/backend/app/celery/tasks/job_execution.py @@ -8,7 +8,7 @@ fail_duplicate_detection) 6 Prompt improvement + iteration graph (run_prompt_improvement, run_evaluation_iteration_graph_step) - 2 Everything else (doctransform, collections, assessment) + 2 Everything else (collections, assessment) 1 Notifications (send_eval_completion_notification) `evaluations`, ordered the same way: @@ -111,21 +111,6 @@ def run_guardrails_job(self, project_id: int, job_id: str, trace_id: str, **kwar ) -@celery_app.task(bind=True, queue="default", priority=2) -@gevent_timeout(settings.CELERY_TASK_SOFT_TIME_LIMIT, "run_doctransform_job") -def run_doctransform_job(self, project_id: int, job_id: str, trace_id: str, **kwargs): - from app.services.doctransform.job import execute_job - - _set_trace(trace_id) - return execute_job( - project_id=project_id, - job_id=job_id, - task_id=current_task.request.id, - task_instance=self, - **kwargs, - ) - - @celery_app.task(bind=True, queue="default", priority=2) @gevent_timeout(settings.CELERY_TASK_SOFT_TIME_LIMIT, "run_collection_setup_job") def run_collection_setup_job( diff --git a/backend/app/celery/utils.py b/backend/app/celery/utils.py index c5514946b..9239d87c3 100644 --- a/backend/app/celery/utils.py +++ b/backend/app/celery/utils.py @@ -91,25 +91,6 @@ def start_guardrails_job( return task_id -def start_doctransform_job( - project_id: int, job_id: str, trace_id: str = "N/A", **kwargs -) -> str: - from app.celery.tasks.job_execution import run_doctransform_job - - task_id = run_doctransform_job.apply_async( - kwargs={ - "project_id": project_id, - "job_id": job_id, - "trace_id": trace_id, - **kwargs, - } - ).id - logger.info( - f"[start_doctransform_job] Started job {job_id} with Celery task {task_id}" - ) - return task_id - - def start_collection_setup_job( project_id: int, job_id: str, trace_id: str = "N/A", **kwargs ) -> str: diff --git a/backend/app/core/config.py b/backend/app/core/config.py index f92ec0c03..84b21a6c3 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -208,7 +208,6 @@ def AWS_S3_BUCKET(self) -> str: PENDING_RECENT_GRACE_MINUTES: int = 3 LLM_PENDING_THRESHOLD_MINUTES: int = 30 COLLECTION_PENDING_THRESHOLD_MINUTES: int = 30 - DOC_TRANSFORMATION_PENDING_THRESHOLD_MINUTES: int = 30 # A fast run stuck in `processing` past this with no chunk progress is stalled; # the cron healer re-enqueues its missing chunk tasks. EVAL_FAST_STALL_THRESHOLD_MINUTES: int = 15 diff --git a/backend/app/core/telemetry/context.py b/backend/app/core/telemetry/context.py index 41b97cdc0..52e8845de 100644 --- a/backend/app/core/telemetry/context.py +++ b/backend/app/core/telemetry/context.py @@ -41,11 +41,9 @@ class LogModuleEnum(StrEnum): # -------- KNOWLEDGEBASE -------- "app.api.routes.collection_job": LogModuleEnum.KNOWLEDGEBASE, "app.api.routes.collections": LogModuleEnum.KNOWLEDGEBASE, - "app.api.routes.doc_transformation_job": LogModuleEnum.KNOWLEDGEBASE, "app.api.routes.documents.document": LogModuleEnum.KNOWLEDGEBASE, "app.crud.collection.collection": LogModuleEnum.KNOWLEDGEBASE, "app.crud.collection.collection_job": LogModuleEnum.KNOWLEDGEBASE, - "app.crud.document.doc_transformation_job": LogModuleEnum.KNOWLEDGEBASE, "app.crud.document.document": LogModuleEnum.KNOWLEDGEBASE, "app.crud.document_collection": LogModuleEnum.KNOWLEDGEBASE, "app.crud.rag.gemini": LogModuleEnum.KNOWLEDGEBASE, @@ -56,8 +54,6 @@ class LogModuleEnum(StrEnum): "app.services.collections.providers.gemini": LogModuleEnum.KNOWLEDGEBASE, "app.services.collections.providers.openai": LogModuleEnum.KNOWLEDGEBASE, "app.services.collections.providers.registry": LogModuleEnum.KNOWLEDGEBASE, - "app.services.doctransform.job": LogModuleEnum.KNOWLEDGEBASE, - "app.services.doctransform.zerox_transformer": LogModuleEnum.KNOWLEDGEBASE, "app.services.documents.helpers": LogModuleEnum.KNOWLEDGEBASE, "app.services.documents.validator": LogModuleEnum.KNOWLEDGEBASE, # -------- LLM_CALL -------- diff --git a/backend/app/crud/__init__.py b/backend/app/crud/__init__.py index 0d4cde1e3..2d12199cc 100644 --- a/backend/app/crud/__init__.py +++ b/backend/app/crud/__init__.py @@ -8,7 +8,6 @@ from .collection.collection_job import CollectionJobCrud from .document.document import DocumentCrud from .document_collection import DocumentCollectionCrud -from .document.doc_transformation_job import DocTransformationJobCrud from .jobs import JobCrud from .organization import ( diff --git a/backend/app/crud/document/doc_transformation_job.py b/backend/app/crud/document/doc_transformation_job.py deleted file mode 100644 index 65285499e..000000000 --- a/backend/app/crud/document/doc_transformation_job.py +++ /dev/null @@ -1,98 +0,0 @@ -import logging -from uuid import UUID - -from fastapi import HTTPException -from sqlmodel import Session, and_, col, select - -from app.core.util import now -from app.models import ( - DocTransformationJob, - DocTransformJobCreate, - DocTransformJobUpdate, -) -from app.models.document import Document - -logger = logging.getLogger(__name__) - - -class DocTransformationJobCrud: - def __init__(self, session: Session, project_id: int): - self.session = session - self.project_id = project_id - - def create(self, payload: DocTransformJobCreate) -> DocTransformationJob: - job = DocTransformationJob(**payload.model_dump()) - self.session.add(job) - self.session.commit() - self.session.refresh(job) - logger.info( - f"[DocTransformationJobCrud.create] Created new transformation job | id: {job.id}, source_document_id: {job.source_document_id}" - ) - return job - - def read_one(self, job_id: UUID) -> DocTransformationJob: - statement = ( - select(DocTransformationJob) - .join( - Document, - col(DocTransformationJob.source_document_id) == col(Document.id), - ) - .where( - and_( - DocTransformationJob.id == job_id, - Document.project_id == self.project_id, - col(Document.deleted_at).is_(None), - ) - ) - ) - - job = self.session.exec(statement).one_or_none() - if not job: - logger.warning( - f"[DocTransformationJobCrud.read_one] Job not found or Document is deleted | id: {job_id}, project_id: {self.project_id}" - ) - raise HTTPException(status_code=404, detail="Transformation job not found") - return job - - def read_each(self, job_ids: set[UUID]) -> list[DocTransformationJob]: - statement = ( - select(DocTransformationJob) - .join( - Document, - col(DocTransformationJob.source_document_id) == col(Document.id), - ) - .where( - and_( - col(DocTransformationJob.id).in_(list(job_ids)), - Document.project_id == self.project_id, - col(Document.deleted_at).is_(None), - ) - ) - ) - - jobs = self.session.exec(statement).all() - return list(jobs) - - def update( - self, - job_id: UUID, - patch: DocTransformJobUpdate, - ) -> DocTransformationJob: - """Update an existing doc transformation job and return the updated row.""" - job = self.read_one(job_id) - - # Only apply fields that were explicitly set and not None - changes = patch.model_dump(exclude_unset=True, exclude_none=True) - for field, value in changes.items(): - setattr(job, field, value) - - job.updated_at = now() - - self.session.add(job) - self.session.commit() - self.session.refresh(job) - - logger.info( - f"[DocTransformationJobCrud.update_status] Updated job status | id: {job.id}" - ) - return job diff --git a/backend/app/crud/job/__init__.py b/backend/app/crud/job/__init__.py index 425245c2b..60dcb72ff 100644 --- a/backend/app/crud/job/__init__.py +++ b/backend/app/crud/job/__init__.py @@ -14,7 +14,6 @@ ) from app.crud.job.pending_monitor import ( count_stale_pending_collection_jobs, - count_stale_pending_doc_transformation_jobs, count_stale_llm_pending_jobs, ) @@ -29,5 +28,4 @@ # Pending-job monitor reads "count_stale_llm_pending_jobs", "count_stale_pending_collection_jobs", - "count_stale_pending_doc_transformation_jobs", ] diff --git a/backend/app/crud/job/pending_monitor.py b/backend/app/crud/job/pending_monitor.py index 0b374cebc..2cadc4434 100644 --- a/backend/app/crud/job/pending_monitor.py +++ b/backend/app/crud/job/pending_monitor.py @@ -13,10 +13,6 @@ from sqlmodel import Session, select from app.models.collection_job import CollectionJob, CollectionJobStatus -from app.models.doc_transformation_job import ( - DocTransformationJob, - TransformationStatus, -) from app.models.job import Job, JobStatus MAX_IDS = 100 @@ -151,38 +147,10 @@ def count_stale_pending_collection_jobs( } -def count_stale_pending_doc_transformation_jobs( - session: Session, - *, - lower_cutoff: datetime, - upper_cutoff: datetime, -) -> StalePendingResult: - """Count DocTransformationJob rows pending inside the window.""" - conditions = ( - DocTransformationJob.status == TransformationStatus.PENDING, - DocTransformationJob.inserted_at <= upper_cutoff, - DocTransformationJob.inserted_at >= lower_cutoff, - ) - stale_count, oldest_at = _count_and_oldest( - session, DocTransformationJob, DocTransformationJob.inserted_at, conditions - ) - ids = _sample_ids( - session, DocTransformationJob, DocTransformationJob.inserted_at, conditions - ) - return { - "stale_count": stale_count, - "oldest_at": oldest_at, - "groups": [], - "ids": ids, - "ids_truncated": stale_count > len(ids), - } - - __all__ = [ "MAX_IDS", "StaleGroup", "StalePendingResult", "count_stale_pending_collection_jobs", - "count_stale_pending_doc_transformation_jobs", "count_stale_llm_pending_jobs", ] diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index bb8ef9dbe..9766412aa 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -106,21 +106,12 @@ CredsPublic, CredsUpdate, ) -from .doc_transformation_job import ( - DocTransformationJob, - DocTransformJobCreate, - DocTransformJobUpdate, - TransformationStatus, -) from .document import ( - DocTransformationJobPublic, - DocTransformationJobsPublic, Document, DocumentPublic, DocumentUploadInitiateResponse, DocumentUploadRequest, DocumentUploadResponse, - TransformationJobInfo, TransformedDocumentPublic, ) from .document_collection import DocumentCollection diff --git a/backend/app/models/doc_transformation_job.py b/backend/app/models/doc_transformation_job.py deleted file mode 100644 index 6f6a658b2..000000000 --- a/backend/app/models/doc_transformation_job.py +++ /dev/null @@ -1,98 +0,0 @@ -import enum -from datetime import datetime -from uuid import UUID, uuid4 - -from pydantic import ConfigDict -from sqlmodel import Field, SQLModel - -from app.core.util import now - - -class TransformationStatus(str, enum.Enum): - PENDING = "PENDING" - PROCESSING = "PROCESSING" - COMPLETED = "COMPLETED" - FAILED = "FAILED" - - -class DocTransformationJob(SQLModel, table=True): - """Database model for DocTransformationJob operations.""" - - __tablename__ = "doc_transformation_job" # pyright: ignore[reportAssignmentType] - - id: UUID = Field( - default_factory=uuid4, - primary_key=True, - sa_column_kwargs={"comment": "Unique identifier for the transformation job"}, - ) - status: TransformationStatus = Field( - default=TransformationStatus.PENDING, - sa_column_kwargs={ - "comment": "Current status (PENDING, PROCESSING, COMPLETED, FAILED)" - }, - ) - task_id: str | None = Field( - default=None, - nullable=True, - sa_column_kwargs={"comment": "Celery task ID for async processing"}, - ) - trace_id: str | None = Field( - default=None, - description="Tracing ID for correlating logs and traces.", - sa_column_kwargs={"comment": "Tracing ID for correlating logs and traces"}, - ) - error_message: str | None = Field( - default=None, - sa_column_kwargs={"comment": "Error message if transformation failed"}, - ) - - # Foreign keys - source_document_id: UUID = Field( - foreign_key="document.id", - ondelete="CASCADE", - sa_column_kwargs={ - "comment": "Reference to the source document being transformed" - }, - ) - transformed_document_id: UUID | None = Field( - default=None, - foreign_key="document.id", - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the resulting transformed document"}, - ) - - # Timestamps - inserted_at: datetime = Field( - default_factory=now, - sa_column_kwargs={"comment": "Timestamp when the job was created"}, - ) - updated_at: datetime = Field( - default_factory=now, - sa_column_kwargs={"comment": "Timestamp when the job was last updated"}, - ) - - @property - def job_id(self) -> UUID: - return self.id - - @property - def job_inserted_at(self) -> datetime: - return self.inserted_at - - @property - def job_updated_at(self) -> datetime: - return self.updated_at - - -class DocTransformJobCreate(SQLModel): - source_document_id: UUID - - model_config = ConfigDict(extra="forbid") # pyright: ignore[reportAssignmentType] - - -class DocTransformJobUpdate(SQLModel): - transformed_document_id: UUID | None = None - task_id: str | None = None - status: TransformationStatus | None = None - error_message: str | None = None - trace_id: str | None = None diff --git a/backend/app/models/document.py b/backend/app/models/document.py index 1623c2f44..f35145251 100644 --- a/backend/app/models/document.py +++ b/backend/app/models/document.py @@ -5,7 +5,6 @@ from sqlmodel import Column, Field, SQLModel from app.core.util import now -from app.models.doc_transformation_job import TransformationStatus class DocumentBase(SQLModel): @@ -101,22 +100,11 @@ class TransformedDocumentPublic(DocumentPublic): ) -class TransformationJobInfo(SQLModel): - message: str - job_id: UUID = Field(description="The unique identifier of the transformation job") - status: TransformationStatus - transformer: str = Field(description="The name of the transformer used") - status_check_url: str = Field( - description="The URL to check the status of the transformation job" - ) - - class DocumentUploadResponse(DocumentPublic): # Intentionally narrows the optional parent field: an upload always returns a URL. signed_url: str = Field( description="A signed URL for accessing the document" ) # pyright: ignore[reportIncompatibleVariableOverride, reportGeneralTypeIssues] - transformation_job: TransformationJobInfo | None = None class DocumentUploadRequest(SQLModel): @@ -138,16 +126,3 @@ class DocumentUploadInitiateResponse(SQLModel): expires_in: int = Field( description="Effective lifetime of the upload URL in seconds, after server-side capping" ) - - -class DocTransformationJobPublic(SQLModel): - job_id: UUID - source_document_id: UUID - status: TransformationStatus - transformed_document: TransformedDocumentPublic | None = None - error_message: str | None = None - - -class DocTransformationJobsPublic(SQLModel): - jobs: list[DocTransformationJobPublic] - jobs_not_found: list[UUID] diff --git a/backend/app/services/doctransform/job.py b/backend/app/services/doctransform/job.py deleted file mode 100644 index d87a38a32..000000000 --- a/backend/app/services/doctransform/job.py +++ /dev/null @@ -1,308 +0,0 @@ -import tempfile -import shutil -import time -import logging -from pathlib import Path -from uuid import uuid4, UUID - -from fastapi import UploadFile -from gevent import Timeout -from celery.exceptions import SoftTimeLimitExceeded -from tenacity import retry, wait_exponential, stop_after_attempt -from sqlmodel import Session -from asgi_correlation_id import correlation_id -from starlette.datastructures import Headers - -from app.crud.document.doc_transformation_job import DocTransformationJobCrud -from app.crud.document.document import DocumentCrud -from app.models import ( - Document, - DocTransformJobUpdate, - TransformationStatus, - DocTransformationJobPublic, - TransformedDocumentPublic, - DocTransformationJob, - Project, -) -from app.core.cloud import get_cloud_storage -from app.celery.utils import start_doctransform_job -from app.utils import send_callback, get_webhook_secret, APIResponse -from app.services.doctransform.registry import convert_document, FORMAT_TO_EXTENSION -from app.core.db import engine - -logger = logging.getLogger(__name__) - - -def start_job( - db: Session, - project_id: int, - job_id: UUID, - transformer_name: str, - target_format: str, - callback_url: str | None, -) -> UUID: - trace_id = correlation_id.get() or "N/A" - job_crud = DocTransformationJobCrud(db, project_id=project_id) - job_crud.update(job_id, DocTransformJobUpdate(trace_id=trace_id)) - job = job_crud.read_one(job_id) - - task_id = start_doctransform_job( - project_id=project_id, - job_id=str(job.id), - trace_id=trace_id, - source_document_id=str(job.source_document_id), - transformer_name=transformer_name, - target_format=target_format, - callback_url=callback_url, - ) - - logger.info( - f"[start_job] Job scheduled for document transformation | id: {job.id}, project_id: {project_id}, task_id: {task_id}" - ) - return job.id - - -def build_success_payload( - job: DocTransformationJob, - transformed_doc: TransformedDocumentPublic, -): - """ - { - "success": true, - "data": { job fields + transformed_document (full) }, - "error": null, - "metadata": null - } - """ - transformed_public = TransformedDocumentPublic.model_validate(transformed_doc) - job_public = DocTransformationJobPublic.model_validate( - job, - update={"transformed_document": transformed_public}, - ) - # keep error_message out of the data envelope - return APIResponse.success_response(job_public).model_dump( - mode="json", exclude={"data": {"error_message"}} - ) - - -def build_failure_payload(job: DocTransformationJob, error_message: str): - """ - { - "success": false, - "data": { job fields, transformed_document: null }, - "error": "something went wrong", - "metadata": null - } - """ - # ensure transformed_document is explicitly null in the payload - job_public = DocTransformationJobPublic.model_validate( - job, - update={"transformed_document": None}, - ) - return APIResponse.failure_response(error_message, job_public).model_dump( - mode="json", - exclude={"data": {"error_message"}}, - ) - - -def _handle_job_failure( - error_message: str, - job_uuid: UUID, - project_id: int, - callback_url: str | None, - webhook_secret: str | None, - job_for_payload: DocTransformationJob | None, - log_context: str = "", -) -> DocTransformationJob | None: - context_suffix = f" on {log_context}" if log_context else "" - try: - with Session(engine) as db: - job_crud = DocTransformationJobCrud(session=db, project_id=project_id) - job_for_payload = job_crud.update( - job_uuid, - DocTransformJobUpdate( - status=TransformationStatus.FAILED, error_message=error_message - ), - ) - except Exception as db_error: - logger.error( - "[doc_transform.execute_job] failed to persist FAILED status%s | job_id=%s | db_error=%s", - context_suffix, - job_uuid, - db_error, - ) - if callback_url and job_for_payload: - try: - failure_payload = build_failure_payload(job_for_payload, error_message) - send_callback(callback_url, failure_payload, webhook_secret=webhook_secret) - except Exception as cb_error: - logger.error( - "[doc_transform.execute_job] callback failed%s | job_id=%s | error=%s", - context_suffix, - job_uuid, - cb_error, - ) - return job_for_payload - - -@retry(wait=wait_exponential(multiplier=5, min=5, max=10), stop=stop_after_attempt(3)) -def execute_job( - project_id: int, - job_id: str, - source_document_id: str, - transformer_name: str, - target_format: str, - task_id: str, - callback_url: str | None, - task_instance, -): - start_time = time.time() - tmp_dir: Path | None = None - - job_for_payload = None # keep latest job snapshot for payloads - webhook_secret: str | None = None - - job_uuid = UUID(job_id) - - try: - source_uuid = UUID(source_document_id) - - if callback_url: - with Session(engine) as db: - project = db.get(Project, project_id) - if project is not None: - webhook_secret = get_webhook_secret(project_id, project.organization_id) - - logger.info( - "[doc_transform.execute_job] started | job_id=%s | transformer=%s | target=%s | project_id=%s", - job_uuid, - transformer_name, - target_format, - project_id, - ) - - with Session(engine) as db: - job_crud = DocTransformationJobCrud(session=db, project_id=project_id) - job_for_payload = job_crud.update( - job_uuid, - DocTransformJobUpdate( - status=TransformationStatus.PROCESSING, task_id=task_id - ), - ) - - doc_crud = DocumentCrud(session=db, project_id=project_id) - source_doc = doc_crud.read_one(source_uuid) - - source_doc_id = source_doc.id - source_doc_fname = source_doc.fname - source_doc_object_store_url = source_doc.object_store_url - - storage = get_cloud_storage(session=db, project_id=project_id) - - # --- download source --- - body = storage.stream(source_doc_object_store_url) - tmp_dir = Path(tempfile.mkdtemp()) - tmp_in = tmp_dir / f"{source_doc_id}" - with open(tmp_in, "wb") as f: - shutil.copyfileobj(body, f) - - # --- transform --- - fname_no_ext = Path(source_doc_fname).stem - target_extension = FORMAT_TO_EXTENSION.get(target_format, f".{target_format}") - transformed_doc_id = uuid4() - tmp_out = tmp_dir / f"{fname_no_ext}{target_extension}" - - convert_document(tmp_in, tmp_out, transformer_name) - - # --- upload transformed file --- - content_type_map = {"markdown": "text/markdown; charset=utf-8"} - content_type = content_type_map.get(target_format, "text/plain") - - with open(tmp_out, "rb") as fobj: - file_upload = UploadFile( - filename=tmp_out.name, - file=fobj, - headers=Headers({"content-type": content_type}), - ) - dest = storage.put(file_upload, Path(str(transformed_doc_id))) - - with Session(engine) as db: - new_doc = Document( - id=transformed_doc_id, - project_id=project_id, - fname=tmp_out.name, - object_store_url=str(dest), - source_document_id=source_doc_id, - ) - created = DocumentCrud(db, project_id).update(new_doc) - - job_crud = DocTransformationJobCrud(session=db, project_id=project_id) - job_for_payload = job_crud.update( - job_uuid, - DocTransformJobUpdate( - status=TransformationStatus.COMPLETED, - transformed_document_id=created.id, - ), - ) - - signed_url = None - try: - get_signed_url = getattr(storage, "get_signed_url", None) - if callable(get_signed_url): - signed_url = get_signed_url(created.object_store_url) - except Exception as e: - logger.warning( - "[doc_transform] failed to generate signed URL for doc %s: %s", - created.id, - e, - ) - - transformed_public = TransformedDocumentPublic.model_validate( - created, - update={"signed_url": signed_url} if signed_url else None, - ) - - success_payload = build_success_payload(job_for_payload, transformed_public) - - elapsed = time.time() - start_time - logger.info( - "[doc_transform.execute_job] completed | job_id=%s | transformed_doc_id=%s | time=%.2fs", - job_uuid, - created.id, - elapsed, - ) - - if callback_url: - send_callback(callback_url, success_payload, webhook_secret=webhook_secret) - - except (Timeout, SoftTimeLimitExceeded) as err: - timeout_err = TimeoutError("Task exceeded soft time limit") - logger.warning( - "[doc_transform.execute_job] Timed Out | job_id=%s", - job_uuid, - ) - _handle_job_failure( - str(timeout_err), - job_uuid, - project_id, - callback_url, - webhook_secret, - job_for_payload, - log_context="timeout", - ) - raise - - except Exception as e: - logger.error( - "[doc_transform.execute_job] FAILED | job_id=%s | error=%s", - job_uuid, - e, - exc_info=True, - ) - _handle_job_failure( - str(e), job_uuid, project_id, callback_url, webhook_secret, job_for_payload - ) - raise - finally: - if tmp_dir and tmp_dir.exists(): - shutil.rmtree(tmp_dir) diff --git a/backend/app/services/doctransform/registry.py b/backend/app/services/doctransform/registry.py deleted file mode 100644 index b0507ce3c..000000000 --- a/backend/app/services/doctransform/registry.py +++ /dev/null @@ -1,140 +0,0 @@ -from pathlib import Path -from gevent import Timeout -from celery.exceptions import SoftTimeLimitExceeded - -from app.services.doctransform.transformer import Transformer -from app.services.doctransform.zerox_transformer import ZeroxTransformer - - -class TransformationError(Exception): - """Raised when a document transformation fails.""" - - -# Map transformer names to their classes -TRANSFORMERS: dict[str, type[Transformer]] = { - "default": ZeroxTransformer, - "zerox": ZeroxTransformer, -} - -# Define supported transformations: (source_format, target_format) -> [available_transformers] -SUPPORTED_TRANSFORMATIONS: dict[tuple[str, str], dict[str, str]] = { - ("pdf", "markdown"): { - "default": "zerox", - "zerox": "zerox", - }, - # Future transformations can be added here - # ("docx", "markdown"): {"default": "pandoc", "pandoc": "pandoc"}, - # ("html", "markdown"): {"default": "pandoc", "pandoc": "pandoc"}, -} - -# Map file extensions to format names -EXTENSION_TO_FORMAT: dict[str, str] = { - ".pdf": "pdf", - ".docx": "docx", - ".doc": "doc", - ".html": "html", - ".htm": "html", - ".txt": "text", - ".md": "markdown", - ".markdown": "markdown", - ".csv": "csv", - ".json": "json", - ".xlsx": "xlsx", - ".xls": "xls", -} - -# Map format names to file extensions -FORMAT_TO_EXTENSION: dict[str, str] = { - "pdf": ".pdf", - "docx": ".docx", - "doc": ".doc", - "html": ".html", - "text": ".txt", - "markdown": ".md", - "csv": ".csv", - "json": ".json", - "xlsx": ".xlsx", - "xls": ".xls", -} - - -def get_file_format(filename: str) -> str: - """Extract format from filename extension.""" - ext = Path(filename).suffix.lower() - format_name = EXTENSION_TO_FORMAT.get(ext) - if not format_name: - raise ValueError(f"Unsupported file extension: {ext}") - return format_name - - -def get_supported_transformations() -> dict[tuple[str, str], set[str]]: - """Get all supported transformation combinations.""" - return { - key: set(transformers.keys()) - for key, transformers in SUPPORTED_TRANSFORMATIONS.items() - } - - -def is_transformation_supported(source_format: str, target_format: str) -> bool: - """Check if a transformation from source_format to target_format is supported.""" - return (source_format, target_format) in SUPPORTED_TRANSFORMATIONS - - -def get_available_transformers( - source_format: str, target_format: str -) -> dict[str, str]: - """Get available transformers for a specific transformation.""" - return SUPPORTED_TRANSFORMATIONS.get((source_format, target_format), {}) - - -def resolve_transformer( - source_format: str, target_format: str, transformer_name: str | None = None -) -> str: - """ - Resolve the actual transformer to use for a transformation. - Returns the transformer name to use. - """ - available_transformers = get_available_transformers(source_format, target_format) - - if not available_transformers: - raise ValueError( - f"Transformation from {source_format} to {target_format} is not supported" - ) - - if transformer_name is None: - transformer_name = "default" - - if transformer_name not in available_transformers: - available = ", ".join(available_transformers.keys()) - raise ValueError( - f"Transformer '{transformer_name}' not available for {source_format} to {target_format}. " - f"Available: {available}" - ) - - return available_transformers[transformer_name] - - -def convert_document( - input_path: Path, output_path: Path, transformer_name: str = "default" -) -> Path: - """ - Select and run the specified transformer on the input_path, writing to output_path. - Returns the path to the transformed file. - """ - try: - transformer_cls = TRANSFORMERS[transformer_name] - except KeyError: - available = ", ".join(TRANSFORMERS.keys()) - raise ValueError( - f"Transformer '{transformer_name}' not found. Available: {available}" - ) - - transformer = transformer_cls() - try: - return transformer.transform(input_path, output_path) - except (Timeout, SoftTimeLimitExceeded): - raise - except Exception as e: - raise TransformationError( - f"Error applying transformer '{transformer_name}': {e}" - ) from e diff --git a/backend/app/services/doctransform/transformer.py b/backend/app/services/doctransform/transformer.py deleted file mode 100644 index ef4babea5..000000000 --- a/backend/app/services/doctransform/transformer.py +++ /dev/null @@ -1,14 +0,0 @@ -from abc import ABC, abstractmethod -from pathlib import Path - - -class Transformer(ABC): - """Abstract base for document transformers.""" - - @abstractmethod - def transform(self, input_path: Path, output_path: Path) -> Path: - """ - Transform the document at input_path and write the result to output_path. - Returns the path to the transformed file. - """ - pass diff --git a/backend/app/services/doctransform/zerox_transformer.py b/backend/app/services/doctransform/zerox_transformer.py deleted file mode 100644 index 82f12ece7..000000000 --- a/backend/app/services/doctransform/zerox_transformer.py +++ /dev/null @@ -1,74 +0,0 @@ -import logging - -from asyncio import Runner, wait_for -from pathlib import Path -from pyzerox import zerox -from gevent import Timeout -from celery.exceptions import SoftTimeLimitExceeded - -from app.services.doctransform.transformer import Transformer - -logger = logging.getLogger(__name__) - - -class ZeroxTransformer(Transformer): - """ - Transformer that uses zerox to extract content from PDFs. - """ - - def __init__(self, model: str = "gpt-4o"): - self.model = model - - def transform(self, input_path: Path, output_path: Path) -> Path: - logger.info(f"ZeroxTransformer Started: (model={self.model})") - if not input_path.exists(): - raise FileNotFoundError(f"Input file not found: {input_path}") - - try: - with Runner() as runner: - result = runner.run( - wait_for( - zerox( - file_path=str(input_path), - model=self.model, - ), - timeout=10 * 60, # 10 minutes - ) - ) - except (Timeout, SoftTimeLimitExceeded): - raise - except TimeoutError: - logger.warning( - f"ZeroxTransformer timed out for {input_path} (model={self.model})" - ) - raise RuntimeError( - f"ZeroxTransformer PDF extraction timed out after {10*60} seconds for {input_path}" - ) - except Exception as e: - logger.error( - f"ZeroxTransformer failed for {input_path}: {e}\n" - "This may be due to a missing Poppler installation or a corrupt PDF file.", - exc_info=True, - ) - raise RuntimeError( - f"Failed to extract content from PDF. " - f"Check that Poppler is installed and in your PATH. Original error: {e}" - ) from e - - if result is None or not hasattr(result, "pages") or result.pages is None: - raise RuntimeError( - "Zerox returned no pages. This may indicate a PDF/image conversion failure " - "(is Poppler installed and in PATH?)" - ) - - with output_path.open("w", encoding="utf-8") as output_file: - for page in result.pages: - if not getattr(page, "content", None): - continue - output_file.write(page.content) - output_file.write("\n\n") - - logger.info( - f"[ZeroxTransformer.transform] Transformation completed, output written to: {output_path}" - ) - return output_path diff --git a/backend/app/services/documents/formats.py b/backend/app/services/documents/formats.py new file mode 100644 index 000000000..38a2e4e1f --- /dev/null +++ b/backend/app/services/documents/formats.py @@ -0,0 +1,25 @@ +from pathlib import Path + +EXTENSION_TO_FORMAT: dict[str, str] = { + ".pdf": "pdf", + ".docx": "docx", + ".doc": "doc", + ".html": "html", + ".htm": "html", + ".txt": "text", + ".md": "markdown", + ".markdown": "markdown", + ".csv": "csv", + ".json": "json", + ".xlsx": "xlsx", + ".xls": "xls", +} + + +def get_file_format(filename: str) -> str: + """Extract format from filename extension.""" + ext = Path(filename).suffix.lower() + format_name = EXTENSION_TO_FORMAT.get(ext) + if not format_name: + raise ValueError(f"Unsupported file extension: {ext}") + return format_name diff --git a/backend/app/services/documents/helpers.py b/backend/app/services/documents/helpers.py index 959b73522..2351ad25d 100644 --- a/backend/app/services/documents/helpers.py +++ b/backend/app/services/documents/helpers.py @@ -1,32 +1,17 @@ import logging -from typing import Optional, Tuple, Iterable, Union -from uuid import UUID +from typing import Iterable, Union from fastapi import HTTPException, UploadFile -from sqlmodel import Session from app.core.cloud.storage import CloudStorage - -from app.services.doctransform.registry import ( - get_available_transformers, - get_file_format, - is_transformation_supported, - resolve_transformer, -) -from app.crud import DocTransformationJobCrud, DocumentCrud -from app.services.doctransform import job as transformation_job +from app.services.documents.formats import get_file_format from app.services.documents.validator import ( DocumentValidationError, validate_document_content, ) from app.models import ( - DocTransformJobCreate, - TransformationStatus, - TransformationJobInfo, Document, DocumentPublic, - DocTransformationJob, - DocTransformationJobPublic, TransformedDocumentPublic, ) @@ -34,26 +19,21 @@ logger = logging.getLogger(__name__) -def validate_upload( - *, - src: UploadFile, - target_format: str | None, - transformer: str | None, -) -> Tuple[str, str | None]: +def validate_upload(*, src: UploadFile) -> str: """ - Full pre-storage gate: extension and transformer validation plus a content - sanity check. Returns (source_format, actual_transformer_or_none). + Full pre-storage gate: extension validation plus a content sanity check. + Returns the source format. - Raises: HTTPException(400) on client errors. + Raises: HTTPException(422) on an unreadable source format, 400 on other + client errors. """ if src.filename is None: raise HTTPException(status_code=400, detail="Uploaded file has no filename") - source_format, actual_transformer = pre_transform_validation( - src_filename=src.filename, - target_format=target_format, - transformer=transformer, - ) + try: + source_format = get_file_format(src.filename) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) try: validate_document_content(file=src, source_format=source_format) @@ -64,7 +44,7 @@ def validate_upload( ) raise HTTPException(status_code=400, detail=e.client_message) - return source_format, actual_transformer + return source_format def calculate_file_size(file: UploadFile) -> float: @@ -87,90 +67,6 @@ def calculate_file_size(file: UploadFile) -> float: return round(size_bytes / 1024) -def pre_transform_validation( - *, - src_filename: str, - target_format: str | None, - transformer: str | None, -) -> Tuple[str, str | None]: - """ - Everything BEFORE storage: - - detect source_format - - validate (source -> target) support if target requested - - resolve actual transformer (or None if no target_format) - - Returns: (source_format, actual_transformer_or_none) - Raises: HTTPException(422) on an unreadable source format, 400 on an - unsupported transformation or transformer. - """ - try: - source_format = get_file_format(src_filename) - except ValueError as e: - raise HTTPException(status_code=422, detail=str(e)) - - actual_transformer: Optional[str] = None - if target_format: - if not is_transformation_supported(source_format, target_format): - raise HTTPException( - status_code=400, - detail=f"Transformation from {source_format} to {target_format} is not supported", - ) - - candidate = transformer or "default" - try: - actual_transformer = resolve_transformer( - source_format, target_format, candidate - ) - except ValueError as e: - available = get_available_transformers(source_format, target_format) - raise HTTPException( - status_code=400, - detail=f"{e}. Available transformers: {list(available.keys())}", - ) - - return source_format, actual_transformer - - -def schedule_transformation( - *, - session: Session, - project_id: int, - source_format: str, - target_format: str | None, - actual_transformer: str | None, - source_document_id: UUID, - callback_url: str | None, -) -> TransformationJobInfo | None: - """ - Everything AFTER the document row is persisted: - - if target was requested and a transformer was resolved, - create the job and enqueue it; return job_info. - - otherwise return None. - """ - if not (target_format and actual_transformer): - return None - - job_crud = DocTransformationJobCrud(session, project_id) - job = job_crud.create(DocTransformJobCreate(source_document_id=source_document_id)) - - transformation_job_id = transformation_job.start_job( - db=session, - job_id=job.id, - project_id=project_id, - transformer_name=actual_transformer, - target_format=target_format, - callback_url=callback_url, - ) - - return TransformationJobInfo( - message=f"Document accepted for transformation from {source_format} to {target_format}.", - job_id=transformation_job_id, - status=TransformationStatus.PENDING, - transformer=actual_transformer, - status_check_url=f"/documents/transformation/{transformation_job_id}", - ) - - PublicDoc = Union[DocumentPublic, TransformedDocumentPublic] @@ -217,54 +113,3 @@ def build_document_schemas( schema.signed_url = _signed_url(doc, storage, download) out.append(schema) return out - - -def build_job_schema( - *, - job: DocTransformationJob, - doc_crud: DocumentCrud, - include_url: bool, - storage: CloudStorage | None, - download: bool = False, -) -> DocTransformationJobPublic: - """Build a single job schema, optionally attaching a signed URL.""" - transformed_doc_schema: TransformedDocumentPublic | None = None - object_url: str | None = None - - if job.transformed_document_id: - doc = doc_crud.read_one(job.transformed_document_id) - transformed_doc_schema = TransformedDocumentPublic.model_validate( - doc, from_attributes=True - ) - object_url = doc.object_store_url - - if include_url and storage and object_url: - transformed_doc_schema.signed_url = _signed_url(doc, storage, download) - - job_schema = DocTransformationJobPublic.model_validate(job, from_attributes=True) - return job_schema.model_copy( - update={"transformed_document": transformed_doc_schema} - ) - - -def build_job_schemas( - *, - jobs: Iterable[DocTransformationJob], - doc_crud: DocumentCrud, - include_url: bool, - storage: CloudStorage | None, - download: bool = False, -) -> list[DocTransformationJobPublic]: - """Build many job schemas efficiently.""" - out: list[DocTransformationJobPublic] = [] - for job in jobs: - out.append( - build_job_schema( - job=job, - doc_crud=doc_crud, - include_url=include_url, - storage=storage, - download=download, - ) - ) - return out diff --git a/backend/app/services/documents/registration.py b/backend/app/services/documents/registration.py index 436b0cbfa..4b0b2eef7 100644 --- a/backend/app/services/documents/registration.py +++ b/backend/app/services/documents/registration.py @@ -11,7 +11,7 @@ from app.core.cloud.storage import PENDING_PREFIX, ObjectNotFoundError from app.crud import DocumentCrud from app.models import Document, DocumentPublic, DocumentUploadInitiateResponse -from app.services.doctransform.registry import get_file_format +from app.services.documents.formats import get_file_format from app.services.documents.constants import ( MAX_UPLOAD_BYTES, UPLOAD_URL_EXPIRY_SECONDS, diff --git a/backend/app/services/job_monitoring.py b/backend/app/services/job_monitoring.py index 36b1a85b3..fe4c0aa23 100644 --- a/backend/app/services/job_monitoring.py +++ b/backend/app/services/job_monitoring.py @@ -13,11 +13,9 @@ StaleGroup, StalePendingResult, count_stale_pending_collection_jobs, - count_stale_pending_doc_transformation_jobs, count_stale_llm_pending_jobs, ) from app.models.collection_job import CollectionJobStatus -from app.models.doc_transformation_job import TransformationStatus from app.models.job import JobStatus logger = logging.getLogger(__name__) @@ -27,7 +25,6 @@ TABLE_DOMAIN_LABEL = { "job": "LLM job", "collection_jobs": "Collection job", - "doc_transformation_job": "Document job", } @@ -227,20 +224,6 @@ def monitor_pending_jobs(session: Session) -> dict[str, Any]: ), as_of=as_of, ), - _build_summary( - table="doc_transformation_job", - status=TransformationStatus.PENDING.value, - threshold_minutes=settings.DOC_TRANSFORMATION_PENDING_THRESHOLD_MINUTES, - result=count_stale_pending_doc_transformation_jobs( - session, - lower_cutoff=as_of - - timedelta( - minutes=settings.DOC_TRANSFORMATION_PENDING_THRESHOLD_MINUTES - ), - upper_cutoff=upper_cutoff, - ), - as_of=as_of, - ), ] for summary in summaries: diff --git a/backend/app/tests/api/routes/documents/test_route_document_upload.py b/backend/app/tests/api/routes/documents/test_route_document_upload.py index ddfdacad0..1dc38eaaa 100644 --- a/backend/app/tests/api/routes/documents/test_route_document_upload.py +++ b/backend/app/tests/api/routes/documents/test_route_document_upload.py @@ -1,10 +1,9 @@ import os import mimetypes -from typing import Any from pathlib import Path from tempfile import NamedTemporaryFile from urllib.parse import urlparse -from unittest.mock import patch, MagicMock +from unittest.mock import patch import pytest from moto import mock_aws @@ -27,23 +26,14 @@ def put( self, route: Route, scratch: Path, - target_format: str = None, - transformer: str = None, ): (mtype, _) = mimetypes.guess_type(str(scratch)) files = {"src": (str(scratch), scratch.open("rb"), mtype)} - data = {} - if target_format: - data["target_format"] = target_format - if transformer: - data["transformer"] = transformer - return self.client.post( str(route), headers={"X-API-KEY": self.user_api_key.key}, files=files, - data=data, ) @@ -54,24 +44,6 @@ def scratch(): yield Path(fp.name) -@pytest.fixture -def pdf_scratch(): - # Create a test PDF file for transformation tests - with NamedTemporaryFile(mode="w", suffix=".pdf", delete=False) as fp: - fp.write("%PDF-1.4\n1 0 obj<>endobj\n") - fp.write("2 0 obj<>endobj\n") - fp.write("3 0 obj<>endobj\n") - fp.write("xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n") - fp.write( - "0000000074 00000 n \n0000000120 00000 n \ntrailer<>\n" - ) - fp.write("startxref\n202\n%%EOF") - fp.flush() - yield Path(fp.name) - # Clean up the temporary file - Path(fp.name).unlink() - - @pytest.fixture def json_scratch(): # Legacy assistants clone .json knowledge-base files @@ -144,164 +116,45 @@ def test_adds_to_S3( assert aws.client.head_object(Bucket=url.netloc, Key=str(key)) - def test_upload_without_transformation( + def test_upload_basic( self, db: Session, route: Route, scratch: Path, uploader: WebUploader, ) -> None: - """Test basic upload without any transformation parameters.""" + """Test basic upload.""" aws = AmazonCloudStorageClient() aws.create() response = httpx_to_standard(uploader.put(route, scratch)) assert response.success is True - assert response.data["transformation_job"] is None + assert "transformation_job" not in response.data assert "id" in response.data assert "fname" in response.data - @patch("app.services.doctransform.job.start_job") - def test_upload_with_transformation( - self, - mock_start_job: Any, - db: Session, - route: Route, - pdf_scratch: Path, - uploader: WebUploader, - ) -> None: - """Test upload with valid transformation parameters.""" - aws = AmazonCloudStorageClient() - aws.create() - - # Mock the background job creation - mock_job_id = "12345678-1234-5678-9abc-123456789012" - mock_start_job.return_value = mock_job_id - - response = httpx_to_standard( - uploader.put(route, pdf_scratch, target_format="markdown") - ) - - assert response.success is True - assert response.data["transformation_job"] is not None - - transformation_job = response.data["transformation_job"] - assert transformation_job["job_id"] == mock_job_id - assert transformation_job["transformer"] == "zerox" # Default transformer - assert ( - transformation_job["status_check_url"] - == f"/documents/transformation/{mock_job_id}" - ) - assert "message" in transformation_job - - @patch("app.services.doctransform.job.start_job") - def test_upload_with_specific_transformer( - self, - mock_start_job: Any, - db: Session, - route: Route, - pdf_scratch: Path, - uploader: WebUploader, - ) -> None: - """Test upload with specific transformer specified.""" - aws = AmazonCloudStorageClient() - aws.create() - - mock_job_id = "12345678-1234-5678-9abc-123456789012" - mock_start_job.return_value = mock_job_id - - response = httpx_to_standard( - uploader.put( - route, pdf_scratch, target_format="markdown", transformer="zerox" - ) - ) - - assert response.success is True - transformation_job = response.data["transformation_job"] - assert transformation_job["transformer"] == "zerox" - - def test_upload_json_without_transformation( + def test_upload_json( self, db: Session, route: Route, json_scratch: Path, uploader: WebUploader, ) -> None: - """Legacy .json knowledge-base files upload without transformation.""" + """Legacy .json knowledge-base files upload.""" aws = AmazonCloudStorageClient() aws.create() response = httpx_to_standard(uploader.put(route, json_scratch)) assert response.success is True - assert response.data["transformation_job"] is None + assert "transformation_job" not in response.data doc_id = response.data["id"] statement = select(Document).where(Document.id == doc_id) result = db.exec(statement).one() assert result.fname == str(json_scratch) - def test_upload_json_with_unsupported_transformation( - self, - db: Session, - route: Route, - json_scratch: Path, - uploader: WebUploader, - ) -> None: - """.json has no transformer; requesting a target format is rejected.""" - aws = AmazonCloudStorageClient() - aws.create() - - response = uploader.put(route, json_scratch, target_format="markdown") - - assert response.status_code == 400 - error_data = response.json() - assert ( - "Transformation from json to markdown is not supported" - in error_data["error"] - ) - - def test_upload_with_unsupported_transformation( - self, - db: Session, - route: Route, - scratch: Path, - uploader: WebUploader, - ) -> None: - """Test upload with unsupported transformation returns error.""" - aws = AmazonCloudStorageClient() - aws.create() - - response = uploader.put(route, scratch, target_format="pdf") - - assert response.status_code == 400 - error_data = response.json() - assert "Transformation from text to pdf is not supported" in error_data["error"] - - def test_upload_with_invalid_transformer( - self, - db: Session, - route: Route, - pdf_scratch: Path, - uploader: WebUploader, - ) -> None: - """Test upload with invalid transformer name returns error.""" - aws = AmazonCloudStorageClient() - aws.create() - - response = uploader.put( - route, - pdf_scratch, - target_format="markdown", - transformer="invalid_transformer", - ) - - assert response.status_code == 400 - error_data = response.json() - assert "Transformer 'invalid_transformer' not available" in error_data["error"] - assert "Available transformers:" in error_data["error"] - def test_upload_with_unsupported_file_extension( self, db: Session, @@ -319,39 +172,13 @@ def test_upload_with_unsupported_file_extension( unsupported_file = Path(fp.name) try: - response = uploader.put(route, unsupported_file, target_format="markdown") + response = uploader.put(route, unsupported_file) assert response.status_code == 422 error_data = response.json() assert "Unsupported file extension: .xyz" in error_data["error"] finally: unsupported_file.unlink() - @patch("app.services.doctransform.job.start_job") - def test_transformation_job_created_in_database( - self, - mock_start_job: Any, - db: Session, - route: Route, - pdf_scratch: Path, - uploader: WebUploader, - ) -> None: - """Test that transformation job is properly stored in the database.""" - aws = AmazonCloudStorageClient() - aws.create() - - mock_job_id = "12345678-1234-5678-9abc-123456789012" - mock_start_job.return_value = mock_job_id - - response = httpx_to_standard( - uploader.put(route, pdf_scratch, target_format="markdown") - ) - - mock_start_job.assert_called_once() - args, kwargs = mock_start_job.call_args - - # Check that start_job was called with the right arguments - assert "transformer_name" in kwargs or len(args) >= 4 - def test_upload_file_within_size_limit( self, db: Session, @@ -396,14 +223,14 @@ def test_upload_file_exceeds_size_limit( assert "exceeds the maximum allowed size" in error_detail assert "25" in error_detail - def test_upload_response_structure_without_transformation( + def test_upload_response_structure( self, db: Session, route: Route, scratch: Path, uploader: WebUploader, ) -> None: - """Test the response structure for upload without transformation.""" + """Test the response structure for upload.""" aws = AmazonCloudStorageClient() aws.create() @@ -419,4 +246,4 @@ def test_upload_response_structure_without_transformation( for field in required_fields: assert field in response.data - assert response.data["transformation_job"] is None + assert "transformation_job" not in response.data diff --git a/backend/app/tests/api/routes/test_doc_transformation_job.py b/backend/app/tests/api/routes/test_doc_transformation_job.py deleted file mode 100644 index 294489b3e..000000000 --- a/backend/app/tests/api/routes/test_doc_transformation_job.py +++ /dev/null @@ -1,375 +0,0 @@ -from fastapi.testclient import TestClient -from sqlmodel import Session - -from app.core.config import settings -from app.crud.document.doc_transformation_job import DocTransformationJobCrud -from app.models import ( - TransformationStatus, - DocTransformJobCreate, - DocTransformJobUpdate, -) -from app.tests.utils.document import DocumentStore -from app.tests.utils.auth import TestAuthContext - - -class TestGetTransformationJob: - def test_get_existing_job_success( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - document = DocumentStore(db, user_api_key.project_id).put() - crud = DocTransformationJobCrud(db, user_api_key.project_id) - created_job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - resp = client.get( - f"{settings.API_V1_STR}/documents/transformation/{created_job.id}", - headers={"X-API-KEY": user_api_key.key}, - ) - assert resp.status_code == 200 - data = resp.json()["data"] - - assert data["job_id"] is not None - assert data["source_document_id"] == str(document.id) - assert data["status"] == TransformationStatus.PENDING - assert data["error_message"] is None - assert data["transformed_document"] is None - - def test_get_nonexistent_job_404( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Test getting a non-existent transformation job returns 404.""" - fake_uuid = "00000000-0000-0000-0000-000000000001" - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation/{fake_uuid}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 404 - - def test_get_job_invalid_uuid_422( - self, client: TestClient, user_api_key: TestAuthContext - ) -> None: - resp = client.get( - f"{settings.API_V1_STR}/documents/transformation/not-a-uuid", - headers={"X-API-KEY": user_api_key.key}, - ) - assert resp.status_code == 422 - body = resp.json() - assert body["errors"] and any( - "valid UUID" in e["message"] for e in body["errors"] - ) - - def test_get_job_different_project_404( - self, - client: TestClient, - db: Session, - user_api_key: TestAuthContext, - superuser_api_key: TestAuthContext, - ) -> None: - """Test that jobs from different projects are not accessible.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation/{job.id}", - headers={"X-API-KEY": superuser_api_key.key}, - ) - - assert response.status_code == 404 - - def test_get_completed_job_with_result( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Test getting a completed job with transformation result.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - source_document = store.put() - transformed_document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=source_document.id)) - - # Update job to completed status - crud.update( - job.id, - DocTransformJobUpdate( - status=TransformationStatus.COMPLETED, - transformed_document_id=transformed_document.id, - ), - ) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation/{job.id}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - data = response.json() - assert data["data"]["status"] == TransformationStatus.COMPLETED - assert data["data"]["transformed_document"]["id"] == str( - transformed_document.id - ) - - def test_get_failed_job_with_error( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Test getting a failed job with error message.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - error_msg = "Transformation failed due to invalid format" - - # Update job to failed status - crud.update( - job.id, - DocTransformJobUpdate( - status=TransformationStatus.FAILED, error_message=error_msg - ), - ) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation/{job.id}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - data = response.json() - assert data["data"]["status"] == TransformationStatus.FAILED - assert data["data"]["error_message"] == error_msg - - -class TestGetMultipleTransformationJobs: - def test_get_multiple_jobs_success( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Test successfully retrieving multiple transformation jobs.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - documents = store.fill(3) - jobs = [ - crud.create(DocTransformJobCreate(source_document_id=doc.id)) - for doc in documents - ] - job_ids_params = "&".join(f"job_ids={job.id}" for job in jobs) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?{job_ids_params}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - data = response.json() - assert "data" in data - assert len(data["data"]["jobs"]) == 3 - assert len(data["data"]["jobs_not_found"]) == 0 - - returned_ids = {job["job_id"] for job in data["data"]["jobs"]} - expected_ids = {str(job.id) for job in jobs} - assert returned_ids == expected_ids - - def test_get_mixed_existing_nonexisting_jobs( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Test retrieving a mix of existing and non-existing jobs.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - documents = store.fill(2) - jobs = [ - crud.create(DocTransformJobCreate(source_document_id=doc.id)) - for doc in documents - ] - fake_uuid = "00000000-0000-0000-0000-000000000001" - - job_ids_params = ( - f"job_ids={jobs[0].id}&job_ids={jobs[1].id}&job_ids={fake_uuid}" - ) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?{job_ids_params}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - data = response.json() - assert len(data["data"]["jobs"]) == 2 - assert len(data["data"]["jobs_not_found"]) == 1 - assert data["data"]["jobs_not_found"][0] == fake_uuid - - def test_get_jobs_with_empty_string( - self, client: TestClient, user_api_key: TestAuthContext - ) -> None: - """Test retrieving jobs with empty job_ids parameter.""" - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?job_ids=", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 422 - body = response.json() - assert body["success"] is False - assert body["data"] is None - assert body["errors"] - assert any( - "valid UUID" in e["message"] or "expected length" in e["message"] - for e in body["errors"] - ) - assert any("job_ids" in e["field"] for e in body["errors"]) - - def test_get_jobs_with_whitespace_only( - self, client: TestClient, user_api_key: TestAuthContext - ) -> None: - """Test retrieving jobs with whitespace-only job_ids.""" - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?job_ids= ", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 422 - body = response.json() - assert body["success"] is False - assert body["data"] is None - assert body["errors"] - assert any("valid UUID" in e["message"] for e in body["errors"]) - - def test_get_jobs_invalid_uuid_format_422( - self, client: TestClient, user_api_key: TestAuthContext - ) -> None: - """Invalid UUID format should return 422 (validation error).""" - invalid_uuid = "not-a-uuid" - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?job_ids={invalid_uuid}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 422 - body = response.json() - assert body["success"] is False - assert body["data"] is None - assert body["errors"] - assert any( - "valid UUID" in e["message"] or "expected length" in e["message"] - for e in body["errors"] - ) - assert any("job_ids" in e["field"] for e in body["errors"]) - - def test_get_jobs_mixed_valid_invalid_uuid_422( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Mixed valid/invalid UUIDs should return 422.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - job_ids_params = f"job_ids={job.id}&job_ids=not-a-uuid" - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?{job_ids_params}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 422 - body = response.json() - assert body["success"] is False - assert body["data"] is None - assert body["errors"] - assert any("job_ids" in e["field"] for e in body["errors"]) - assert any( - "valid UUID" in e["message"] - or "invalid character" in e["message"] - or "invalid length" in e["message"] - for e in body["errors"] - ) - - def test_get_jobs_missing_parameter_422( - self, client: TestClient, user_api_key: TestAuthContext - ) -> None: - """Missing job_ids parameter should 422 (Query(min=1)).""" - response = client.get( - f"{settings.API_V1_STR}/documents/transformation", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 422 - body = response.json() - assert body["success"] is False - assert body["data"] is None - assert body["errors"] - assert any("Field required" in e["message"] for e in body["errors"]) - assert any("job_ids" in e["field"] for e in body["errors"]) - - def test_get_jobs_different_project_not_found( - self, - client: TestClient, - db: Session, - user_api_key: TestAuthContext, - superuser_api_key: TestAuthContext, - ) -> None: - """Jobs from different projects are not returned.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?job_ids={job.id}", - headers={"X-API-KEY": superuser_api_key.key}, - ) - - assert response.status_code == 200 - data = response.json() - assert len(data["data"]["jobs"]) == 0 - assert len(data["data"]["jobs_not_found"]) == 1 - assert data["data"]["jobs_not_found"][0] == str(job.id) - - def test_get_jobs_with_various_statuses( - self, client: TestClient, db: Session, user_api_key: TestAuthContext - ) -> None: - """Test retrieving jobs with different statuses.""" - store = DocumentStore(db, user_api_key.project_id) - crud = DocTransformationJobCrud(db, user_api_key.project_id) - documents = store.fill(4) - jobs = [ - crud.create(DocTransformJobCreate(source_document_id=doc.id)) - for doc in documents - ] - - crud.update( - jobs[1].id, DocTransformJobUpdate(status=TransformationStatus.PROCESSING) - ) - crud.update( - jobs[2].id, - DocTransformJobUpdate( - status=TransformationStatus.COMPLETED, - transformed_document_id=documents[2].id, - ), - ) - crud.update( - jobs[3].id, - DocTransformJobUpdate( - status=TransformationStatus.FAILED, - error_message="Test error", - ), - ) - - job_ids_params = "&".join(f"job_ids={job.id}" for job in jobs) - - response = client.get( - f"{settings.API_V1_STR}/documents/transformation?{job_ids_params}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - data = response.json() - assert len(data["data"]["jobs"]) == 4 - - statuses = {job["status"] for job in data["data"]["jobs"]} - expected_statuses = { - TransformationStatus.PENDING, - TransformationStatus.PROCESSING, - TransformationStatus.COMPLETED, - TransformationStatus.FAILED, - } - assert statuses == expected_statuses diff --git a/backend/app/tests/api/test_auth_failures.py b/backend/app/tests/api/test_auth_failures.py index dc31612a6..d49deb9bd 100644 --- a/backend/app/tests/api/test_auth_failures.py +++ b/backend/app/tests/api/test_auth_failures.py @@ -19,10 +19,6 @@ (f"{settings.API_V1_STR}/documents", "POST"), (f"{settings.API_V1_STR}/documents/12345678-1234-5678-1234-567812345678", "GET"), (f"{settings.API_V1_STR}/documents/12345678-1234-5678-1234-567812345678", "DELETE"), - ( - f"{settings.API_V1_STR}/documents/transformation/12345678-1234-5678-1234-567812345678", - "GET", - ), (f"{settings.API_V1_STR}/cron/evaluations", "GET"), (f"{settings.API_V1_STR}/cron/pending-jobs", "GET"), (f"{settings.API_V1_STR}/evaluations/datasets", "POST"), diff --git a/backend/app/tests/celery/test_job_execution.py b/backend/app/tests/celery/test_job_execution.py index 5c11f67e7..dec4be87d 100644 --- a/backend/app/tests/celery/test_job_execution.py +++ b/backend/app/tests/celery/test_job_execution.py @@ -14,7 +14,6 @@ ("run_llm_job", "app.services.llm.jobs.execute_job"), ("run_llm_chain_job", "app.services.llm.jobs.execute_chain_job"), ("run_guardrails_job", "app.services.guardrails.jobs.execute_job"), - ("run_doctransform_job", "app.services.doctransform.job.execute_job"), ( "run_collection_setup_job", "app.services.collections.create_collection.execute_setup_job", diff --git a/backend/app/tests/celery/test_utils.py b/backend/app/tests/celery/test_utils.py index 5476db763..6af8b2faa 100644 --- a/backend/app/tests/celery/test_utils.py +++ b/backend/app/tests/celery/test_utils.py @@ -14,7 +14,6 @@ ("start_llm_job", "run_llm_job", JOB_KWARGS, JOB_KWARGS), ("start_llm_chain_job", "run_llm_chain_job", JOB_KWARGS, JOB_KWARGS), ("start_guardrails_job", "run_guardrails_job", JOB_KWARGS, JOB_KWARGS), - ("start_doctransform_job", "run_doctransform_job", JOB_KWARGS, JOB_KWARGS), ( "start_collection_setup_job", "run_collection_setup_job", diff --git a/backend/app/tests/core/telemetry/sentry/test_sentry_filters.py b/backend/app/tests/core/telemetry/sentry/test_sentry_filters.py index ba6bb2633..d8b8c85d5 100644 --- a/backend/app/tests/core/telemetry/sentry/test_sentry_filters.py +++ b/backend/app/tests/core/telemetry/sentry/test_sentry_filters.py @@ -312,7 +312,7 @@ def test_redacts_query_for_chain_job(self) -> None: def test_ignores_unrelated_tasks(self) -> None: event = self._event_with_celery_job( - "app.celery.tasks.job_execution.run_doctransform_job", + "app.celery.tasks.job_execution.run_collection_setup_job", {"request_data": {"query": {"input": "not an llm job"}}}, ) diff --git a/backend/app/tests/crud/documents/test_doc_transformation_job.py b/backend/app/tests/crud/documents/test_doc_transformation_job.py deleted file mode 100644 index f5f5ba74d..000000000 --- a/backend/app/tests/crud/documents/test_doc_transformation_job.py +++ /dev/null @@ -1,272 +0,0 @@ -import pytest -from sqlmodel import Session -from sqlalchemy.exc import IntegrityError - -from app.crud.document.doc_transformation_job import DocTransformationJobCrud -from app.models import ( - TransformationStatus, - DocTransformJobCreate, - DocTransformJobUpdate, -) -from app.core.exception_handlers import HTTPException -from app.core.util import now -from app.tests.utils.document import DocumentStore -from app.tests.utils.utils import get_project, SequentialUuidGenerator -from app.tests.utils.test_data import create_test_project - - -@pytest.fixture -def store(db: Session) -> DocumentStore: - project = get_project(db) - return DocumentStore(db, project.id) - - -@pytest.fixture -def crud(db: Session, store: DocumentStore) -> DocTransformationJobCrud: - return DocTransformationJobCrud(db, store.project.id) - - -class TestDocTransformationJobCrudCreate: - def test_can_create_job_with_valid_document( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - document = store.put() - - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - assert job.id is not None - assert job.source_document_id == document.id - assert job.status == TransformationStatus.PENDING - assert job.error_message is None - assert job.transformed_document_id is None - assert job.inserted_at is not None - assert job.updated_at is not None - - def test_cannot_create_job_with_invalid_document( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - """With FK enforced, creating with a non-existent document should fail at commit.""" - invalid_id = next(SequentialUuidGenerator()) - - with pytest.raises(IntegrityError): - crud.create(DocTransformJobCreate(source_document_id=invalid_id)) - - def test_cannot_create_job_with_deleted_document( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - """ - Creation itself will succeed (FK exists), but later reads should treat it as not found - because read filters out deleted documents. - """ - document = store.put() - document.deleted_at = now() - db.add(document) - db.commit() - - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - # read_one should 404 due to soft-deleted joined document - with pytest.raises(HTTPException) as exc_info: - crud.read_one(job.id) - assert exc_info.value.status_code == 404 - assert "Transformation job not found" in str(exc_info.value.detail) - - -class TestDocTransformationJobCrudReadOne: - def test_can_read_existing_job( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - result = crud.read_one(job.id) - - assert result.id == job.id - assert result.source_document_id == document.id - assert result.status == TransformationStatus.PENDING - - def test_cannot_read_nonexistent_job( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - invalid_id = next(SequentialUuidGenerator()) - - with pytest.raises(HTTPException) as exc_info: - crud.read_one(invalid_id) - - assert exc_info.value.status_code == 404 - assert "Transformation job not found" in str(exc_info.value.detail) - - def test_cannot_read_job_with_deleted_document( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - document.deleted_at = now() - db.add(document) - db.commit() - - with pytest.raises(HTTPException) as exc_info: - crud.read_one(job.id) - - assert exc_info.value.status_code == 404 - assert "Transformation job not found" in str(exc_info.value.detail) - - def test_cannot_read_job_from_different_project( - self, db: Session, store: DocumentStore - ) -> None: - document = store.put() - job_crud = DocTransformationJobCrud(db, store.project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - other_project = create_test_project(db) - other_crud = DocTransformationJobCrud(db, other_project.id) - - with pytest.raises(HTTPException) as exc_info: - other_crud.read_one(job.id) - - assert exc_info.value.status_code == 404 - assert "Transformation job not found" in str(exc_info.value.detail) - - -class TestDocTransformationJobCrudReadEach: - def test_can_read_multiple_existing_jobs( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - documents = store.fill(3) - jobs = [ - crud.create(DocTransformJobCreate(source_document_id=doc.id)) - for doc in documents - ] - job_ids = {job.id for job in jobs} - - results = crud.read_each(job_ids) - - assert len(results) == 3 - result_ids = {job.id for job in results} - assert result_ids == job_ids - - def test_read_partial_existing_jobs( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - documents = store.fill(2) - jobs = [ - crud.create(DocTransformJobCreate(source_document_id=doc.id)) - for doc in documents - ] - job_ids = {job.id for job in jobs} - job_ids.add(next(SequentialUuidGenerator())) # non-existent - - results = crud.read_each(job_ids) - - assert len(results) == 2 - result_ids = {job.id for job in results} - assert result_ids == {job.id for job in jobs} - - def test_read_empty_job_set( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - results = crud.read_each(set()) - assert len(results) == 0 - - def test_cannot_read_jobs_from_different_project( - self, db: Session, store: DocumentStore - ) -> None: - document = store.put() - job_crud = DocTransformationJobCrud(db, store.project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - other_project = get_project(db, name="Dalgo") - other_crud = DocTransformationJobCrud(db, other_project.id) - - results = other_crud.read_each({job.id}) - assert len(results) == 0 - - -class TestDocTransformationJobCrudUpdateStatus: - def test_can_update_status_to_processing( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - updated = crud.update( - job.id, - DocTransformJobUpdate(status=TransformationStatus.PROCESSING), - ) - - assert updated.id == job.id - assert updated.status == TransformationStatus.PROCESSING - assert updated.updated_at >= job.updated_at - - def test_can_update_status_to_completed_with_result( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - source_document = store.put() - transformed_document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=source_document.id)) - - updated = crud.update( - job.id, - DocTransformJobUpdate( - status=TransformationStatus.COMPLETED, - transformed_document_id=transformed_document.id, - ), - ) - - assert updated.status == TransformationStatus.COMPLETED - assert updated.transformed_document_id == transformed_document.id - assert updated.error_message is None - - def test_can_update_status_to_failed_with_error( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - error_msg = "Transformation failed due to invalid format" - - updated = crud.update( - job.id, - DocTransformJobUpdate( - status=TransformationStatus.FAILED, - error_message=error_msg, - ), - ) - - assert updated.status == TransformationStatus.FAILED - assert updated.error_message == error_msg - assert updated.transformed_document_id is None - - def test_cannot_update_nonexistent_job( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - invalid_id = next(SequentialUuidGenerator()) - - with pytest.raises(HTTPException) as exc_info: - crud.update( - invalid_id, - DocTransformJobUpdate(status=TransformationStatus.PROCESSING), - ) - - assert exc_info.value.status_code == 404 - assert "Transformation job not found" in str(exc_info.value.detail) - - def test_update_preserves_existing_fields( - self, db: Session, store: DocumentStore, crud: DocTransformationJobCrud - ) -> None: - """Fields not present in the patch must be preserved by `update`.""" - document = store.put() - job = crud.create(DocTransformJobCreate(source_document_id=document.id)) - - crud.update( - job.id, - DocTransformJobUpdate( - status=TransformationStatus.FAILED, error_message="Initial error" - ), - ) - - updated = crud.update( - job.id, DocTransformJobUpdate(status=TransformationStatus.PROCESSING) - ) - - assert updated.status == TransformationStatus.PROCESSING - assert updated.error_message == "Initial error" diff --git a/backend/app/tests/services/doctransformer/test_job/conftest.py b/backend/app/tests/services/doctransformer/test_job/conftest.py deleted file mode 100644 index 8787db17a..000000000 --- a/backend/app/tests/services/doctransformer/test_job/conftest.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -Pytest fixtures for document transformation service tests. -""" -import os -from typing import Any, Callable, Generator, Tuple -from unittest.mock import patch - -import pytest -from fastapi import BackgroundTasks -from sqlmodel import Session -from tenacity import retry, stop_after_attempt, wait_fixed - -from app.crud import get_project_by_id -from app.services.doctransform import job -from app.core.config import settings -from app.models import Document, Project, AuthContext -from app.tests.utils.document import DocumentStore -from app.tests.utils.auth import TestAuthContext - - -@pytest.fixture(scope="class") -def aws_credentials() -> None: - """Set up AWS credentials for moto.""" - os.environ["AWS_ACCESS_KEY_ID"] = "testing" - os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" - os.environ["AWS_SECURITY_TOKEN"] = "testing" - os.environ["AWS_SESSION_TOKEN"] = "testing" - os.environ["AWS_DEFAULT_REGION"] = settings.AWS_DEFAULT_REGION - - -@pytest.fixture -def fast_execute_job() -> ( - Generator[ - Callable[[int, str, str, str, str, str, str | None, Any], Any], None, None - ] -): - """Create a version of execute_job without retry delays for faster testing.""" - - original_execute_job = job.execute_job - - @retry( - stop=stop_after_attempt(2), wait=wait_fixed(0.01) - ) # Very fast retry for tests - def fast_execute_job_func( - project_id: int, - job_id: str, - source_document_id: str, - transformer_name: str, - target_format: str, - task_id: str, - callback_url: str | None, - task_instance, - ) -> Any: - # Call the original function's implementation without the decorator - return original_execute_job.__wrapped__( - project_id, - job_id, - source_document_id, - transformer_name, - target_format, - task_id, - callback_url, - task_instance, - ) - - with patch.object(job, "execute_job", fast_execute_job_func): - yield fast_execute_job_func - - -@pytest.fixture -def current_user(db: Session, user_api_key: TestAuthContext) -> AuthContext: - """Create a test user for testing.""" - return AuthContext( - user=user_api_key.user, - organization=user_api_key.organization, - project=user_api_key.project, - ) - - -@pytest.fixture -def background_tasks() -> BackgroundTasks: - """Create BackgroundTasks instance.""" - return BackgroundTasks() - - -@pytest.fixture -def test_document(db: Session, current_user: AuthContext) -> Tuple[Document, Project]: - """Create a test document for the current user's project.""" - store = DocumentStore(db, current_user.project.id) - project = get_project_by_id(session=db, project_id=current_user.project.id) - return store.put(), project diff --git a/backend/app/tests/services/doctransformer/test_job/test_callbacks.py b/backend/app/tests/services/doctransformer/test_job/test_callbacks.py deleted file mode 100644 index e090a2224..000000000 --- a/backend/app/tests/services/doctransformer/test_job/test_callbacks.py +++ /dev/null @@ -1,568 +0,0 @@ -""" -Tests for doctransform execute_job: callbacks, payload builders, signed URL, and tmp dir cleanup. - -All existing tests pass callback_url=None. This file covers the gaps: -- success / failure callbacks (payload structure, single send, webhook secret) -- build_success_payload / build_failure_payload -- tmp dir cleaned up in both success and failure paths -- signed URL included when storage supports it; exception swallowed when it doesn't -""" -import shutil -from datetime import datetime -from io import BytesIO -from typing import Tuple -from unittest.mock import MagicMock, patch -from uuid import uuid4 - -import pytest -from moto import mock_aws -from sqlmodel import Session - -from app.crud import DocTransformationJobCrud -from app.models import ( - Document, - DocTransformJobCreate, - Project, - TransformationStatus, - TransformedDocumentPublic, -) -from app.services.doctransform.job import ( - build_failure_payload, - build_success_payload, - execute_job, -) -from app.tests.services.doctransformer.test_job.utils import ( - DocTransformTestBase, - MockTestTransformer, -) - - -def _make_transformed_doc(document: Document) -> TransformedDocumentPublic: - return TransformedDocumentPublic( - id=uuid4(), - project_id=document.project_id, - fname="output.md", - object_store_url="s3://bucket/key", - source_document_id=document.id, - inserted_at=datetime.utcnow(), - updated_at=datetime.utcnow(), - ) - - -# --------------------------------------------------------------------------- -# Payload builders — pure logic, no S3 -# --------------------------------------------------------------------------- - - -class TestBuildPayloads: - def test_success_payload_structure( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - payload = build_success_payload(job, _make_transformed_doc(document)) - - assert payload["success"] is True - assert payload["error"] is None - assert "error_message" not in payload["data"] - assert payload["data"]["transformed_document"]["fname"] == "output.md" - - def test_failure_payload_structure( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - payload = build_failure_payload(job, "conversion crashed") - - assert payload["success"] is False - assert "conversion crashed" in payload["error"] - assert "error_message" not in payload["data"] - assert payload["data"]["transformed_document"] is None - - -# --------------------------------------------------------------------------- -# Callback — success path -# --------------------------------------------------------------------------- - - -class TestCallbacksSuccess(DocTransformTestBase): - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_success_sends_callback_once_with_correct_payload( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - callback_url = "https://example.com/webhook" - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.job.get_webhook_secret", return_value=None - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=callback_url, - task_instance=None, - ) - - mock_send.assert_called_once() - url_arg, payload_arg = mock_send.call_args.args - assert url_arg == callback_url - assert payload_arg["success"] is True - assert payload_arg["data"]["status"] == TransformationStatus.COMPLETED - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_success_callback_not_sent_without_callback_url( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - mock_send.assert_not_called() - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_webhook_secret_passed_to_send_callback( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.job.get_webhook_secret", - return_value="my-secret", - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url="https://example.com/webhook", - task_instance=None, - ) - - assert mock_send.call_args.kwargs["webhook_secret"] == "my-secret" - - -# --------------------------------------------------------------------------- -# Callback — failure path -# --------------------------------------------------------------------------- - - -class TestCallbacksFailure(DocTransformTestBase): - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_failure_sends_callback_with_error_payload( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.job.get_webhook_secret", return_value=None - ), - patch( - "app.services.doctransform.job.convert_document", - side_effect=RuntimeError("converter crashed"), - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - with pytest.raises(RuntimeError): - execute_job.__wrapped__( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url="https://example.com/webhook", - task_instance=None, - ) - - mock_send.assert_called_once() - url_arg, payload_arg = mock_send.call_args.args - assert payload_arg["success"] is False - assert "converter crashed" in payload_arg["error"] - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_failure_callback_not_sent_without_callback_url( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.job.convert_document", - side_effect=RuntimeError("crash"), - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - with pytest.raises(RuntimeError): - execute_job.__wrapped__( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - mock_send.assert_not_called() - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_failure_marks_job_failed_before_callback( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback"), - patch( - "app.services.doctransform.job.get_webhook_secret", return_value=None - ), - patch( - "app.services.doctransform.job.convert_document", - side_effect=RuntimeError("crash"), - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - with pytest.raises(RuntimeError): - execute_job.__wrapped__( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url="https://example.com/webhook", - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "crash" in job.error_message - - -# --------------------------------------------------------------------------- -# Tmp dir cleanup -# --------------------------------------------------------------------------- - - -class TestTmpDirCleanup(DocTransformTestBase): - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_tmp_dir_removed_on_success( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - removed: list[str] = [] - real_rmtree = shutil.rmtree - - def capture(path, **kw): - removed.append(str(path)) - real_rmtree(path, **kw) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.shutil.rmtree", side_effect=capture), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - assert len(removed) == 1 - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_tmp_dir_removed_on_failure( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - removed: list[str] = [] - real_rmtree = shutil.rmtree - - def capture(path, **kw): - removed.append(str(path)) - real_rmtree(path, **kw) - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.shutil.rmtree", side_effect=capture), - patch( - "app.services.doctransform.job.convert_document", - side_effect=RuntimeError("crash"), - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - with pytest.raises(RuntimeError): - execute_job.__wrapped__( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - assert len(removed) == 1 - - -# --------------------------------------------------------------------------- -# Signed URL -# --------------------------------------------------------------------------- - - -class TestSignedUrl(DocTransformTestBase): - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_signed_url_included_in_callback_when_available( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - mock_storage = MagicMock() - mock_storage.stream.return_value = BytesIO(b"content") - mock_storage.put.return_value = "s3://bucket/transformed" - mock_storage.get_signed_url.return_value = "https://signed.example.com/doc" - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.job.get_webhook_secret", return_value=None - ), - patch( - "app.services.doctransform.job.get_cloud_storage", - return_value=mock_storage, - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url="https://example.com/webhook", - task_instance=None, - ) - - payload = mock_send.call_args.args[1] - assert ( - payload["data"]["transformed_document"]["signed_url"] - == "https://signed.example.com/doc" - ) - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_signed_url_exception_swallowed_job_still_succeeds( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job = DocTransformationJobCrud(db, project_id=project.id).create( - DocTransformJobCreate(source_document_id=document.id) - ) - - mock_storage = MagicMock() - mock_storage.stream.return_value = BytesIO(b"content") - mock_storage.put.return_value = "s3://bucket/transformed" - mock_storage.get_signed_url.side_effect = Exception("token expired") - - with ( - patch("app.services.doctransform.job.Session") as mock_session, - patch("app.services.doctransform.job.send_callback") as mock_send, - patch( - "app.services.doctransform.job.get_webhook_secret", return_value=None - ), - patch( - "app.services.doctransform.job.get_cloud_storage", - return_value=mock_storage, - ), - patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), - ): - mock_session.return_value.__enter__.return_value = db - mock_session.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url="https://example.com/webhook", - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - payload = mock_send.call_args.args[1] - assert payload["data"]["transformed_document"]["signed_url"] is None diff --git a/backend/app/tests/services/doctransformer/test_job/test_execute_job.py b/backend/app/tests/services/doctransformer/test_job/test_execute_job.py deleted file mode 100644 index 97aef7c0e..000000000 --- a/backend/app/tests/services/doctransformer/test_job/test_execute_job.py +++ /dev/null @@ -1,306 +0,0 @@ -from typing import Any, Callable, Tuple -from unittest.mock import patch -from uuid import uuid4 - -import pytest -from moto import mock_aws -from sqlmodel import Session -from tenacity import RetryError - -from app.crud import DocTransformationJobCrud, DocumentCrud -from app.services.doctransform.registry import TransformationError -from app.services.doctransform.job import execute_job -from app.core.exception_handlers import HTTPException -from app.models import Document, Project, TransformationStatus, DocTransformJobCreate -from app.tests.services.doctransformer.test_job.utils import ( - DocTransformTestBase, - MockTestTransformer, -) - - -class TestExecuteJob(DocTransformTestBase): - """Test cases for the execute_job function.""" - - @pytest.mark.parametrize( - "target_format, expected_extension", - [ - ("markdown", ".md"), - ("text", ".txt"), - ("html", ".html"), - ], - ) - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_success( - self, - db: Session, - test_document: Tuple[Document, Project], - target_format: str, - expected_extension: str, - ) -> None: - """Test successful document transformation with multiple formats.""" - document, project = test_document - aws = self.setup_aws_s3() - - source_content = b"This is a test document for transformation." - self.create_s3_document_content(aws, document, source_content) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format=target_format, - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - assert job.transformed_document_id is not None - assert job.error_message is None - - document_crud = DocumentCrud(session=db, project_id=project.id) - transformed_doc = document_crud.read_one(job.transformed_document_id) - assert transformed_doc is not None - assert transformed_doc.fname.endswith(expected_extension) - assert "" in transformed_doc.fname - assert transformed_doc.source_document_id == document.id - assert transformed_doc.object_store_url is not None - - self.verify_s3_content(aws, transformed_doc) - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_with_nonexistent_job( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test job execution with non-existent job ID.""" - _, project = test_document - self.setup_aws_s3() - nonexistent_job_id = uuid4() - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - # Execute job should fail because job doesn't exist - with pytest.raises((HTTPException, RetryError)): - fast_execute_job( - project_id=project.id, - job_id=str(nonexistent_job_id), - source_document_id=str(uuid4()), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_with_missing_source_document( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test job execution when source document is missing from S3.""" - document, project = test_document - self.setup_aws_s3() - - # Create job but don't upload document to S3 - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - with pytest.raises(Exception): - fast_execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert job.error_message is not None - assert job.transformed_document_id is None - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_with_transformer_error( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test job execution when transformer raises an error.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - # Mock convert_document to raise TransformationError - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.job.convert_document" - ) as mock_convert, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - mock_convert.side_effect = TransformationError("Mock transformation error") - - # Due to retry mechanism, it will raise RetryError after exhausting retries - with pytest.raises((TransformationError, RetryError)): - fast_execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "Mock transformation error" in job.error_message - assert job.transformed_document_id is None - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_status_transitions( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - """Test that job status transitions correctly during execution.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - initial_status = job.status - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - # Verify status progression by checking final job state - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - assert initial_status == TransformationStatus.PENDING - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_with_different_content_types( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - """Test job execution produces correct content types for different formats.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - format_extensions = [ - ("markdown", "text/markdown", ".md"), - ("text", "text/plain", ".txt"), - ("html", "text/html", ".html"), - ("unknown", "text/plain", ".unknown"), # Default fallback - ] - - for ( - target_format, - expected_content_type, - expected_extension, - ) in format_extensions: - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format=target_format, - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - # Verify transformation completed and check file extension - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - document_crud = DocumentCrud(session=db, project_id=project.id) - assert job.transformed_document_id is not None - transformed_doc = document_crud.read_one(job.transformed_document_id) - assert transformed_doc is not None - assert transformed_doc.fname.endswith(expected_extension) diff --git a/backend/app/tests/services/doctransformer/test_job/test_execute_job_errors.py b/backend/app/tests/services/doctransformer/test_job/test_execute_job_errors.py deleted file mode 100644 index a8f0bf63e..000000000 --- a/backend/app/tests/services/doctransformer/test_job/test_execute_job_errors.py +++ /dev/null @@ -1,331 +0,0 @@ -from io import BytesIO -from uuid import uuid4 -from typing import Any, Callable, Tuple -from unittest.mock import patch - -import pytest -from gevent import Timeout -from moto import mock_aws -from sqlmodel import Session - -from app.crud import DocTransformationJobCrud -from app.models import Document, Project, TransformationStatus, DocTransformJobCreate -from app.services.doctransform.job import execute_job -from app.tests.services.doctransformer.test_job.utils import ( - DocTransformTestBase, - MockTestTransformer, -) -from app.tests.services.doctransformer.test_job.utils import ( - create_failing_convert_document, - create_persistent_failing_convert_document, -) - - -class TestExecuteJobRetryAndErrors(DocTransformTestBase): - """Test cases for retry mechanisms and error handling in execute_job function.""" - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_with_storage_error( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test job execution when S3 upload fails.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - # Mock storage.put to raise an error - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.job.get_cloud_storage" - ) as mock_storage_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - mock_storage = mock_storage_class.return_value - mock_storage.stream.return_value = BytesIO(b"test content") - mock_storage.put.side_effect = Exception("S3 upload failed") - - with pytest.raises(Exception): - fast_execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - # Verify job was marked as failed - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "S3 upload failed" in job.error_message - assert job.transformed_document_id is None - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_retry_mechanism( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test that retry mechanism works for transient failures.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - # Create a side effect that fails once then succeeds (fast retry will only try 2 times) - failing_convert_document = create_failing_convert_document(fail_count=1) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.job.convert_document", - side_effect=failing_convert_document, - ), patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - fast_execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - # Verify the function was retried and eventually succeeded - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_exhausted_retries( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test behavior when all retry attempts are exhausted.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - # Mock convert_document to always fail - persistent_failing_convert_document = ( - create_persistent_failing_convert_document("Persistent error") - ) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.job.convert_document", - side_effect=persistent_failing_convert_document, - ), patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - with pytest.raises(Exception): - fast_execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - # Verify job was marked as failed after retries - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "Persistent error" in job.error_message - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_database_error_during_completion( - self, - db: Session, - test_document: Tuple[Document, Project], - fast_execute_job: Callable[ - [int, str, str, str, str, str, str | None, Any], Any - ], - ) -> None: - """Test handling of database errors when updating job completion.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - # Mock DocumentCrud.update to fail when creating the transformed document - with patch( - "app.services.doctransform.job.DocumentCrud" - ) as mock_doc_crud_class: - mock_doc_crud_instance = mock_doc_crud_class.return_value - mock_doc_crud_instance.read_one.return_value = ( - document # Return valid document for source - ) - mock_doc_crud_instance.update.side_effect = Exception( - "Database error during document creation" - ) - - with pytest.raises(Exception): - fast_execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - # Verify job was marked as failed - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "Database error during document creation" in job.error_message - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_timeout_marks_job_failed( - self, - db: Session, - test_document: Tuple[Document, Project], - ) -> None: - """Test that a gevent Timeout marks the job FAILED with a soft-time-limit message.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.job.get_cloud_storage" - ) as mock_storage_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - mock_storage = mock_storage_class.return_value - mock_storage.stream.side_effect = Timeout(300) - - with pytest.raises(Timeout): - execute_job.__wrapped__( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "soft time limit" in job.error_message - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_timeout_sends_failure_callback( - self, - db: Session, - test_document: Tuple[Document, Project], - ) -> None: - """Test that a gevent Timeout sends a failure callback when callback_url is set.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - callback_url = "https://example.com/doctransform/timeout" - - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.job.get_cloud_storage" - ) as mock_storage_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ), patch( - "app.services.doctransform.job.send_callback" - ) as mock_send_callback: - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - mock_storage = mock_storage_class.return_value - mock_storage.stream.side_effect = Timeout(300) - - with pytest.raises(Timeout): - execute_job.__wrapped__( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=callback_url, - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.FAILED - assert "soft time limit" in job.error_message - - mock_send_callback.assert_called_once() - cb_url_arg, payload_arg = mock_send_callback.call_args.args - assert cb_url_arg == callback_url - assert payload_arg["success"] is False - assert "soft time limit" in (payload_arg["error"] or "") diff --git a/backend/app/tests/services/doctransformer/test_job/test_integration.py b/backend/app/tests/services/doctransformer/test_job/test_integration.py deleted file mode 100644 index 46edcb950..000000000 --- a/backend/app/tests/services/doctransformer/test_job/test_integration.py +++ /dev/null @@ -1,174 +0,0 @@ -from typing import Tuple -from uuid import uuid4 -from unittest.mock import patch - -import pytest -from moto import mock_aws -from sqlmodel import Session - -from app.crud import DocTransformationJobCrud, DocumentCrud -from app.services.doctransform.job import execute_job, start_job -from app.models import ( - Document, - Project, - TransformationStatus, - DocTransformJobCreate, -) -from app.tests.services.doctransformer.test_job.utils import ( - DocTransformTestBase, - MockTestTransformer, -) - - -class TestExecuteJobIntegration(DocTransformTestBase): - """Integration tests for execute_job function with minimal mocking.""" - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_end_to_end_workflow( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - """Test complete end-to-end workflow from start_job to execute_job.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - - with patch( - "app.services.doctransform.job.start_doctransform_job", - return_value="fake-task-id", - ), patch("app.services.doctransform.job.Session") as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - returned_job_id = start_job( - db=db, - project_id=project.id, - job_id=job.id, - transformer_name="test", - target_format="markdown", - callback_url=None, - ) - assert job.id == returned_job_id - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - assert job.transformed_document_id is not None - - document_crud = DocumentCrud(session=db, project_id=project.id) - transformed_doc = document_crud.read_one(job.transformed_document_id) - assert transformed_doc.source_document_id == document.id - assert "" in transformed_doc.fname - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_execute_job_concurrent_jobs( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - """Test multiple concurrent job executions don't interfere with each other.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - # Create multiple jobs - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - jobs = [] - for i in range(3): - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - jobs.append(job) - - for job in jobs: - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format="markdown", - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - for job in jobs: - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - assert job.transformed_document_id is not None - - @mock_aws - @pytest.mark.usefixtures("aws_credentials") - def test_multiple_format_transformations( - self, db: Session, test_document: Tuple[Document, Project] - ) -> None: - """Test transforming the same document to multiple formats.""" - document, project = test_document - aws = self.setup_aws_s3() - self.create_s3_document_content(aws, document) - - formats = ["markdown", "text", "html"] - jobs = [] - - job_crud = DocTransformationJobCrud(session=db, project_id=project.id) - for target_format in formats: - job = job_crud.create(DocTransformJobCreate(source_document_id=document.id)) - jobs.append((job, target_format)) - - for job, target_format in jobs: - with patch( - "app.services.doctransform.job.Session" - ) as mock_session_class, patch( - "app.services.doctransform.registry.TRANSFORMERS", - {"test": MockTestTransformer}, - ): - mock_session_class.return_value.__enter__.return_value = db - mock_session_class.return_value.__exit__.return_value = None - - execute_job( - project_id=project.id, - job_id=str(job.id), - source_document_id=str(document.id), - transformer_name="test", - target_format=target_format, - task_id=str(uuid4()), - callback_url=None, - task_instance=None, - ) - - document_crud = DocumentCrud(session=db, project_id=project.id) - for i, (job, target_format) in enumerate(jobs): - db.refresh(job) - assert job.status == TransformationStatus.COMPLETED - assert job.transformed_document_id is not None - - transformed_doc = document_crud.read_one(job.transformed_document_id) - assert transformed_doc is not None - if target_format == "markdown": - assert transformed_doc.fname.endswith(".md") - elif target_format == "text": - assert transformed_doc.fname.endswith(".txt") - elif target_format == "html": - assert transformed_doc.fname.endswith(".html") diff --git a/backend/app/tests/services/doctransformer/test_job/test_start_job.py b/backend/app/tests/services/doctransformer/test_job/test_start_job.py deleted file mode 100644 index 375392fd6..000000000 --- a/backend/app/tests/services/doctransformer/test_job/test_start_job.py +++ /dev/null @@ -1,184 +0,0 @@ -from unittest.mock import patch -from uuid import uuid4 - -import pytest -from sqlmodel import Session - -from app.services.doctransform.job import start_job -from app.services.doctransform.registry import TRANSFORMERS -from app.core.exception_handlers import HTTPException -from app.crud import DocTransformationJobCrud -from app.models import ( - Document, - DocTransformationJob, - Project, - TransformationStatus, - AuthContext, - DocTransformJobCreate, -) -from app.tests.services.doctransformer.test_job.utils import ( - DocTransformTestBase, - MockTestTransformer, -) - - -class TestStartJob(DocTransformTestBase): - """Test cases for the start_job function.""" - - def _create_job(self, db: Session, project_id: int, source_document_id): - job = DocTransformJobCreate(source_document_id=source_document_id) - job = DocTransformationJobCrud(db, project_id=project_id).create(job) - return job - - def test_start_job_success( - self, - db: Session, - current_user: AuthContext, - test_document: tuple[Document, Project], - ) -> None: - """start_job should enqueue execute_job with correct kwargs and return the same job id.""" - document, _project = test_document - - job = self._create_job(db, current_user.project.id, document.id) - - with patch( - "app.services.doctransform.job.start_doctransform_job" - ) as mock_schedule: - mock_schedule.return_value = "fake-task-id" - - returned_job_id = start_job( - db=db, - project_id=current_user.project.id, - job_id=job.id, - transformer_name="test-transformer", - target_format="markdown", - callback_url=None, - ) - - assert returned_job_id == job.id - - job = db.get(DocTransformationJob, job.id) - assert job is not None - assert job.source_document_id == document.id - assert job.status == TransformationStatus.PENDING - assert job.error_message is None - assert job.transformed_document_id is None - - mock_schedule.assert_called_once() - kwargs = mock_schedule.call_args.kwargs - assert kwargs["project_id"] == current_user.project.id - assert kwargs["job_id"] == str(job.id) - assert kwargs["source_document_id"] == str(job.source_document_id) - assert kwargs["transformer_name"] == "test-transformer" - assert kwargs["target_format"] == "markdown" - assert kwargs["callback_url"] is None - - def test_start_job_with_nonexistent_document( - self, - db: Session, - current_user: AuthContext, - ) -> None: - """ - Previously: start_job validated document and raised 404. - Now: start_job expects an existing job; the equivalent negative case is a non-existent JOB. - """ - nonexistent_job_id = uuid4() - - with pytest.raises(HTTPException): - with patch( - "app.services.doctransform.job.start_doctransform_job" - ) as mock_schedule: - mock_schedule.return_value = "fake-task-id" - start_job( - db=db, - project_id=current_user.project.id, - job_id=nonexistent_job_id, - transformer_name="test-transformer", - target_format="markdown", - callback_url=None, - ) - - def test_start_job_with_different_formats( - self, - db: Session, - current_user: AuthContext, - test_document: tuple[Document, Project], - monkeypatch, - ) -> None: - """Ensure start_job passes target_format through to the scheduler.""" - monkeypatch.setitem(TRANSFORMERS, "test", MockTestTransformer) - - document, _ = test_document - formats = ["markdown", "text", "html"] - - with patch( - "app.services.doctransform.job.start_doctransform_job" - ) as mock_schedule: - mock_schedule.return_value = "fake-task-id" - - for target_format in formats: - job = self._create_job(db, current_user.project.id, document.id) - - returned_job_id = start_job( - db=db, - project_id=current_user.project.id, - job_id=job.id, - transformer_name="test", - target_format=target_format, - callback_url=None, - ) - - # job row still PENDING - job = db.get(DocTransformationJob, job.id) - assert job is not None - assert job.status == TransformationStatus.PENDING - - # scheduler called with correct kwargs - kwargs = mock_schedule.call_args.kwargs - assert kwargs["target_format"] == target_format - assert kwargs["project_id"] == current_user.project.id - assert kwargs["job_id"] == str(job.id) - assert kwargs["source_document_id"] == str(job.source_document_id) - assert kwargs["transformer_name"] == "test" - assert returned_job_id == job.id # new start_job returns the same UUID - - @pytest.mark.parametrize("transformer_name", ["test"]) - def test_start_job_with_different_transformers( - self, - db: Session, - current_user: AuthContext, - test_document: tuple[Document, Project], - transformer_name: str, - monkeypatch, - ) -> None: - """Ensure start_job passes transformer_name through to the scheduler.""" - monkeypatch.setitem(TRANSFORMERS, "test", MockTestTransformer) - - document, _ = test_document - job = self._create_job(db, current_user.project.id, document.id) - - with patch( - "app.services.doctransform.job.start_doctransform_job" - ) as mock_schedule: - mock_schedule.return_value = "fake-task-id" - - returned_job_id = start_job( - db=db, - project_id=current_user.project.id, - job_id=job.id, - transformer_name=transformer_name, - target_format="markdown", - callback_url=None, - ) - - job = db.get(DocTransformationJob, job.id) - assert job is not None - assert job.status == TransformationStatus.PENDING - - kwargs = mock_schedule.call_args.kwargs - assert kwargs["transformer_name"] == transformer_name - assert kwargs["target_format"] == "markdown" - assert kwargs["project_id"] == current_user.project.id - assert kwargs["job_id"] == str(job.id) - assert kwargs["source_document_id"] == str(job.source_document_id) - assert returned_job_id == job.id diff --git a/backend/app/tests/services/doctransformer/test_job/utils.py b/backend/app/tests/services/doctransformer/test_job/utils.py deleted file mode 100644 index 277c5208c..000000000 --- a/backend/app/tests/services/doctransformer/test_job/utils.py +++ /dev/null @@ -1,98 +0,0 @@ -""" -Base test class for DocTransform service tests. - -This module contains DocTransformTestBase with common AWS S3 setup and utilities. -All fixtures are automatically available from conftest.py in the same directory. -""" -from pathlib import Path -from urllib.parse import urlparse - -from app.core.cloud import AmazonCloudStorageClient -from app.core.config import settings -from app.services.doctransform.transformer import Transformer -from app.models import Document - - -class MockTestTransformer(Transformer): - """ - A mock transformer for testing that returns a hardcoded lorem ipsum string. - """ - - def transform(self, input_path: Path, output_path: Path) -> Path: - content = ( - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " - "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." - ) - output_path.write_text(content, encoding="utf-8") - return output_path - - -class DocTransformTestBase: - """Base class for document transformation tests with common setup and utilities.""" - - def setup_aws_s3(self) -> AmazonCloudStorageClient: - """Setup AWS S3 for testing.""" - aws = AmazonCloudStorageClient() - aws.create() - return aws - - def create_s3_document_content( - self, - aws: AmazonCloudStorageClient, - document: Document, - content: bytes = b"Test document content", - ) -> bytes: - """Create content in S3 for a document.""" - parsed_url = urlparse(document.object_store_url) - s3_key = parsed_url.path.lstrip("/") - - aws.client.put_object(Bucket=settings.AWS_S3_BUCKET, Key=s3_key, Body=content) - return content - - def verify_s3_content( - self, - aws: AmazonCloudStorageClient, - transformed_doc: Document, - expected_content: str = None, - ) -> None: - """Verify the content stored in S3.""" - if expected_content is None: - expected_content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." - - parsed_url = urlparse(transformed_doc.object_store_url) - transformed_key = parsed_url.path.lstrip("/") - - response = aws.client.get_object( - Bucket=settings.AWS_S3_BUCKET, Key=transformed_key - ) - transformed_content = response["Body"].read().decode("utf-8") - assert transformed_content == expected_content - - -def create_failing_convert_document(fail_count: int = 1): - """Create a side effect function that fails specified times then succeeds.""" - call_count = 0 - - def failing_convert_document(*args, **kwargs): - nonlocal call_count - call_count += 1 - if call_count <= fail_count: - raise Exception("Transient error") - output_path = args[1] if len(args) > 1 else kwargs.get("output_path") - if output_path: - output_path.write_text("Success after retries", encoding="utf-8") - return output_path - raise ValueError("output_path is required") - - return failing_convert_document - - -def create_persistent_failing_convert_document( - error_message: str = "Persistent error", -): - """Create a side effect function that always fails.""" - - def persistent_failing_convert_document(*args, **kwargs): - raise Exception(error_message) - - return persistent_failing_convert_document diff --git a/backend/app/tests/services/doctransformer/test_registry.py b/backend/app/tests/services/doctransformer/test_registry.py deleted file mode 100644 index ece9b1e40..000000000 --- a/backend/app/tests/services/doctransformer/test_registry.py +++ /dev/null @@ -1,122 +0,0 @@ -import pytest -from celery.exceptions import SoftTimeLimitExceeded -from gevent import Timeout - -from app.services.doctransform.registry import ( - get_file_format, - get_supported_transformations, - is_transformation_supported, - get_available_transformers, - resolve_transformer, - convert_document, - TransformationError, - TRANSFORMERS, -) - - -# Fixture for patching supported transformations -@pytest.fixture -def patched_transformations(monkeypatch): - mapping = { - ("docx", "pdf"): {"default": "pandoc", "pandoc": "pandoc"}, - ("pdf", "markdown"): {"default": "zerox", "zerox": "zerox"}, - } - monkeypatch.setattr( - "app.services.doctransform.registry.SUPPORTED_TRANSFORMATIONS", mapping - ) - return mapping - - -def test_get_file_format_valid(): - assert get_file_format("file.pdf") == "pdf" - assert get_file_format("file.docx") == "docx" - assert get_file_format("file.md") == "markdown" - assert get_file_format("file.html") == "html" - assert get_file_format("file.json") == "json" - - -def test_get_file_format_json_case_insensitive(): - assert get_file_format("legacy_assistant.JSON") == "json" - - -def test_get_file_format_invalid(): - with pytest.raises(ValueError): - get_file_format("file.unknown") - - -def test_get_supported_transformations(patched_transformations): - supported = get_supported_transformations() - assert ("docx", "pdf") in supported - assert "default" in supported[("docx", "pdf")] - assert ("pdf", "markdown") in supported - assert "zerox" in supported[("pdf", "markdown")] - - -def test_is_transformation_supported(monkeypatch): - monkeypatch.setattr( - "app.services.doctransform.registry.SUPPORTED_TRANSFORMATIONS", - {("docx", "pdf"): {"default": "pandoc"}}, - ) - assert is_transformation_supported("docx", "pdf") - assert not is_transformation_supported("pdf", "docx") - - -def test_get_available_transformers(patched_transformations): - transformers = get_available_transformers("docx", "pdf") - assert "default" in transformers - assert "pandoc" in transformers - assert get_available_transformers("pdf", "docx") == {} - - -def test_resolve_transformer(patched_transformations): - assert resolve_transformer("docx", "pdf") == "pandoc" - assert resolve_transformer("docx", "pdf", "pandoc") == "pandoc" - with pytest.raises(ValueError): - resolve_transformer("docx", "pdf", "notfound") - with pytest.raises(ValueError): - resolve_transformer("pdf", "docx") - - -def test_convert_document(tmp_path, monkeypatch): - class DummyTransformer: - def transform(self, input_path, output_path): - output_path.write_text("transformed") - return output_path - - monkeypatch.setitem(TRANSFORMERS, "dummy", DummyTransformer) - input_file = tmp_path / "input.txt" - output_file = tmp_path / "output.txt" - input_file.write_text("test") - result = convert_document(input_file, output_file, transformer_name="dummy") - assert result.read_text() == "transformed" - - # Transformer not found - with pytest.raises(ValueError): - convert_document(input_file, output_file, transformer_name="notfound") - - # Transformer raises error - class FailingTransformer: - def transform(self, input_path, output_path): - raise Exception("fail") - - monkeypatch.setitem(TRANSFORMERS, "fail", FailingTransformer) - with pytest.raises(TransformationError): - convert_document(input_file, output_file, transformer_name="fail") - - # gevent Timeout propagates without being wrapped - class TimeoutTransformer: - def transform(self, input_path, output_path): - raise Timeout() - - monkeypatch.setitem(TRANSFORMERS, "timeout", TimeoutTransformer) - with pytest.raises(Timeout): - convert_document(input_file, output_file, transformer_name="timeout") - - # Celery SoftTimeLimitExceeded propagates without being wrapped - class SoftLimitTransformer: - def transform(self, input_path, output_path): - raise SoftTimeLimitExceeded() - - monkeypatch.setitem(TRANSFORMERS, "softlimit", SoftLimitTransformer) - with pytest.raises(SoftTimeLimitExceeded): - convert_document(input_file, output_file, transformer_name="softlimit") diff --git a/backend/app/tests/services/documents/test_formats.py b/backend/app/tests/services/documents/test_formats.py new file mode 100644 index 000000000..a0cd65878 --- /dev/null +++ b/backend/app/tests/services/documents/test_formats.py @@ -0,0 +1,20 @@ +import pytest + +from app.services.documents.formats import get_file_format + + +def test_get_file_format_valid() -> None: + assert get_file_format("file.pdf") == "pdf" + assert get_file_format("file.docx") == "docx" + assert get_file_format("file.md") == "markdown" + assert get_file_format("file.html") == "html" + assert get_file_format("file.json") == "json" + + +def test_get_file_format_json_case_insensitive() -> None: + assert get_file_format("legacy_assistant.JSON") == "json" + + +def test_get_file_format_invalid() -> None: + with pytest.raises(ValueError): + get_file_format("file.unknown") diff --git a/backend/app/tests/services/documents/test_helpers.py b/backend/app/tests/services/documents/test_helpers.py index 0e5f9d766..4fa3c8d3d 100644 --- a/backend/app/tests/services/documents/test_helpers.py +++ b/backend/app/tests/services/documents/test_helpers.py @@ -305,41 +305,27 @@ def test_valid_pdf_dispatches_to_checker_and_passes(self) -> None: class TestValidateUpload: - def test_valid_csv_returns_format_and_transformer(self, monkeypatch) -> None: - monkeypatch.setattr( - "app.services.documents.helpers.pre_transform_validation", - lambda **kwargs: ("csv", None), - ) - result = validate_upload( - src=make_upload_file(b"a,b,c\n1,2,3\n"), - target_format=None, - transformer=None, - ) - assert result == ("csv", None) - - def test_invalid_content_raises_http_400_with_client_message( - self, monkeypatch - ) -> None: - monkeypatch.setattr( - "app.services.documents.helpers.pre_transform_validation", - lambda **kwargs: ("csv", None), - ) + def test_valid_csv_returns_format(self) -> None: + result = validate_upload(src=make_upload_file(b"a,b,c\n1,2,3\n")) + assert result == "csv" + + def test_unsupported_extension_raises_http_422(self) -> None: with pytest.raises(HTTPException) as exc: - validate_upload( - src=make_upload_file(b"a,b\x00,c\n"), - target_format=None, - transformer=None, - ) + validate_upload(src=make_upload_file(b"data", filename="file.xyz")) + assert exc.value.status_code == 422 + assert "Unsupported file extension: .xyz" in exc.value.detail + + def test_invalid_content_raises_http_400_with_client_message(self) -> None: + with pytest.raises(HTTPException) as exc: + validate_upload(src=make_upload_file(b"a,b\x00,c\n")) assert exc.value.status_code == 400 assert "NUL byte" not in exc.value.detail assert "corrupted" in exc.value.detail - -class TestValidateUpload: def test_missing_filename_raises_400(self) -> None: src = UploadFile(file=BytesIO(b"data"), filename=None) with pytest.raises(HTTPException) as exc_info: - validate_upload(src=src, target_format=None, transformer=None) + validate_upload(src=src) assert exc_info.value.status_code == 400 assert exc_info.value.detail == "Uploaded file has no filename" diff --git a/backend/app/tests/services/test_job_monitoring.py b/backend/app/tests/services/test_job_monitoring.py index 42694bfc6..ed0224f3b 100644 --- a/backend/app/tests/services/test_job_monitoring.py +++ b/backend/app/tests/services/test_job_monitoring.py @@ -8,12 +8,9 @@ CollectionActionType, CollectionJob, CollectionJobStatus, - DocTransformationJob, - Document, Job, JobStatus, JobType, - TransformationStatus, ) from app.services.job_monitoring import monitor_pending_jobs from app.tests.utils.test_data import create_test_project @@ -24,7 +21,6 @@ def _table(result: dict, table_name: str) -> dict: def _clear_job_monitor_tables(db: Session) -> None: - db.exec(delete(DocTransformationJob)) db.exec(delete(CollectionJob)) db.exec(delete(Job)) db.commit() @@ -37,17 +33,6 @@ def test_monitor_pending_jobs_reports_stale_pending_rows(db: Session) -> None: stale_at = now() - timedelta(minutes=20) fresh_at = now() - timedelta(minutes=1) - document = Document( - project_id=project.id, - fname="source.pdf", - object_store_url="s3://test/source.pdf", - inserted_at=stale_at, - updated_at=stale_at, - ) - db.add(document) - db.commit() - db.refresh(document) - db.add_all( [ Job( @@ -59,7 +44,7 @@ def test_monitor_pending_jobs_reports_stale_pending_rows(db: Session) -> None: ), Job( project_id=project.id, - job_type=JobType.RESPONSE, + job_type=JobType.LLM_CHAIN, status=JobStatus.PENDING, inserted_at=stale_at, updated_at=stale_at, @@ -85,18 +70,6 @@ def test_monitor_pending_jobs_reports_stale_pending_rows(db: Session) -> None: inserted_at=fresh_at, updated_at=fresh_at, ), - DocTransformationJob( - source_document_id=document.id, - status=TransformationStatus.PENDING, - inserted_at=stale_at, - updated_at=stale_at, - ), - DocTransformationJob( - source_document_id=document.id, - status=TransformationStatus.PENDING, - inserted_at=fresh_at, - updated_at=fresh_at, - ), ] ) db.commit() @@ -108,13 +81,13 @@ def test_monitor_pending_jobs_reports_stale_pending_rows(db: Session) -> None: result = monitor_pending_jobs(db) assert result["status"] == "ok" - assert result["total_stale_pending"] == 4 + assert result["total_stale_pending"] == 3 job_summary = _table(result, "job") assert job_summary["stale_count"] == 2 assert {group["job_type"] for group in job_summary["groups"]} == { JobType.LLM_API.value, - JobType.RESPONSE.value, + JobType.LLM_CHAIN.value, } collection_summary = _table(result, "collection_jobs") @@ -123,26 +96,18 @@ def test_monitor_pending_jobs_reports_stale_pending_rows(db: Session) -> None: CollectionActionType.CREATE.value ) - doc_summary = _table(result, "doc_transformation_job") - assert doc_summary["stale_count"] == 1 - assert record_metric.called - assert capture_event.call_count == 3 + assert capture_event.call_count == 2 events = [call.args[0] for call in capture_event.call_args_list] by_table = {event["contexts"]["pending_jobs"]["table"]: event for event in events} - assert set(by_table) == {"job", "collection_jobs", "doc_transformation_job"} + assert set(by_table) == {"job", "collection_jobs"} assert by_table["job"]["fingerprint"] == ["pending-jobs", "job", "PENDING"] assert by_table["job"]["tags"]["job.table"] == "job" assert by_table["job"]["contexts"]["pending_jobs"]["stale_count"] == 2 assert by_table["collection_jobs"]["contexts"]["pending_jobs"]["stale_count"] == 1 - assert ( - by_table["doc_transformation_job"]["contexts"]["pending_jobs"]["stale_count"] - == 1 - ) expected_titles = { "job": "LLM job pending for longer than expected", "collection_jobs": "Collection job pending for longer than expected", - "doc_transformation_job": ("Document job pending for longer than expected"), } for table, event in by_table.items(): assert event["message"] == expected_titles[table] @@ -158,15 +123,6 @@ def test_monitor_pending_jobs_ignores_fresh_and_non_pending_rows( stale_at = now() - timedelta(minutes=20) fresh_at = now() - timedelta(minutes=1) - document = Document( - project_id=project.id, - fname="source.pdf", - object_store_url="s3://test/source.pdf", - ) - db.add(document) - db.commit() - db.refresh(document) - db.add_all( [ Job( @@ -204,18 +160,6 @@ def test_monitor_pending_jobs_ignores_fresh_and_non_pending_rows( inserted_at=stale_at, updated_at=stale_at, ), - DocTransformationJob( - source_document_id=document.id, - status=TransformationStatus.PENDING, - inserted_at=fresh_at, - updated_at=fresh_at, - ), - DocTransformationJob( - source_document_id=document.id, - status=TransformationStatus.COMPLETED, - inserted_at=stale_at, - updated_at=stale_at, - ), ] ) db.commit() @@ -229,7 +173,6 @@ def test_monitor_pending_jobs_ignores_fresh_and_non_pending_rows( assert result["total_stale_pending"] == 0 assert _table(result, "job")["stale_count"] == 0 assert _table(result, "collection_jobs")["stale_count"] == 0 - assert _table(result, "doc_transformation_job")["stale_count"] == 0 capture_event.assert_not_called() @@ -240,15 +183,6 @@ def test_monitor_pending_jobs_ignores_rows_older_than_upper_threshold( project = create_test_project(db) ancient_at = now() - timedelta(minutes=45) - document = Document( - project_id=project.id, - fname="source.pdf", - object_store_url="s3://test/source.pdf", - ) - db.add(document) - db.commit() - db.refresh(document) - db.add_all( [ Job( @@ -265,12 +199,6 @@ def test_monitor_pending_jobs_ignores_rows_older_than_upper_threshold( inserted_at=ancient_at, updated_at=ancient_at, ), - DocTransformationJob( - source_document_id=document.id, - status=TransformationStatus.PENDING, - inserted_at=ancient_at, - updated_at=ancient_at, - ), ] ) db.commit() diff --git a/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md b/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md index 681f1d671..810813a1c 100644 --- a/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md +++ b/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md @@ -115,7 +115,7 @@ backend/app/ │ │ ├── base.py BaseProvider ABC (upload_files · create · delete) │ │ ├── openai.py OpenAIProvider (Files API + Vector Stores) │ │ └── registry.py LLMProvider registry · get_llm_provider() -│ └── documents/helpers.py upload validation · schedule_transformation · schema builders +│ └── documents/helpers.py upload validation · schema builders │ ├── celery/ │ ├── tasks/job_execution.py run_collection_setup_job · run_collection_batch_job · @@ -156,18 +156,13 @@ sequenceDiagram participant V as helpers (validation) participant S3 as Object storage participant DB as PostgreSQL - participant T as schedule_transformation - C->>R: multipart file (+ optional target_format / transformer / callback_url) - R->>V: pre_transform_validation(filename, target_format, transformer) + C->>R: multipart file + R->>V: validate_upload(src) → extension + content sanity check R->>V: calculate_file_size() → reject if > MAX_DOC_SIZE_MB (25 MB) → 413 R->>S3: storage.put(src, Path(document_id)) R->>DB: DocumentCrud.update(Document{id, fname, file_size_kb, object_store_url}) - opt transformation requested - R->>T: schedule a doc-transformation Celery job - Note over T: produces a derived Document with source_document_id - end - R-->>C: 200 {document_id, signed_url, transformation_job?} + R-->>C: 200 {document_id, signed_url} ``` What lands in the DB ([models/document.py](../../backend/app/models/document.py)): @@ -178,7 +173,7 @@ What lands in the DB ([models/document.py](../../backend/app/models/document.py) | `object_store_url` | S3 location of the raw bytes | | `file_size_kb` | used later for batch sizing | | `openai_file_id` | **null on upload** — filled lazily the first time the doc is pushed to OpenAI (§7) | -| `source_document_id` | set only for transformation outputs (lineage) | +| `source_document_id` | set only on legacy transformation outputs (lineage); document transformation has been removed | | `deleted_at` | soft-delete marker | Notes: @@ -186,11 +181,6 @@ Notes: - Upload is **synchronous** and **one document per request**. To build a knowledge base from many files, the caller uploads each file, collects the returned IDs, then calls `/collections` once with the full ID list. -- **Transformations** (e.g. `docx → md`) are a separate subsystem. When - requested, a transform job runs on Celery and emits a *new* `document` row - (with `source_document_id` pointing at the original). The knowledge base is - built from whichever document IDs the caller ultimately passes to - `/collections`. - Max **per-document** size is `MAX_DOC_SIZE_MB = 25 MB` ([services/collections/helpers.py](../../backend/app/services/collections/helpers.py)); larger uploads are rejected with `413`. @@ -531,8 +521,8 @@ is DB + storage only; it never touches collections or the provider: - `DELETE /documents/{id}` sets `deleted_at` on the row. Bytes stay in S3. The document drops out of document endpoints and of `GET /collections/{id}?include_docs=true`. - `DELETE /documents/{id}/permanent` deletes the S3 object, then the row. Rows - that reference the document (transformed documents, `doc_transformation_job`, - `fine_tuning`, `model_evaluation`, `document_collection`) go via + that reference the document (legacy transformed documents, `fine_tuning`, + `model_evaluation`, `document_collection`) go via `ON DELETE CASCADE`. Soft-deleted documents can be purged too. Collections that contain the document keep their vector stores and provider diff --git a/docs/wiki/INDEX.md b/docs/wiki/INDEX.md index aa8f5133f..83ce11467 100644 --- a/docs/wiki/INDEX.md +++ b/docs/wiki/INDEX.md @@ -19,7 +19,7 @@ Deep design narrative lives in `docs/architecture/*.md`; open those only for des - [modules/llm-call.md](modules/llm-call.md) — `POST /llm/call` pipeline, configs (`Config`/`ConfigVersion`, `LLMCallConfig`), guardrails, chains. Deep dive: `docs/architecture/kaapi-llm-call-ARCHITECTURE.md` - [modules/guardrails.md](modules/guardrails.md) — guardrails service integration: `POST /guardrails` async job, inline input/output hooks, management proxies, fail-open/fail-closed matrix. Deep dive: `docs/architecture/kaapi-llm-call-ARCHITECTURE.md` §7 (stale on auth failures). - [modules/evaluations.md](modules/evaluations.md) — text/STT/TTS evals, datasets, runs, batch + cron scoring, fast evals. Deep dive: `docs/architecture/kaapi-evaluations-ARCHITECTURE.md` -- [modules/knowledge-base.md](modules/knowledge-base.md) — documents, collections, transforms, vector-store providers. Deep dive: `docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md` +- [modules/knowledge-base.md](modules/knowledge-base.md) — documents, collections, vector-store providers. Deep dive: `docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md` - [modules/assistants.md](modules/assistants.md) — OpenAI assistants and threads. No deep-dive doc yet. - [modules/assessment.md](modules/assessment.md) — assessments and assessment runs. No deep-dive doc yet. - [modules/chatbot.md](modules/chatbot.md) — chatbots as versioned React Flow graphs (draft/publish) with per-conversation sessions; onboarding agent with per-turn field extraction + completion status (`/chatbots`, `/chatbots/{id}/flow*`, `/chatbots/*sessions*` via Celery + webhook; LangGraph + Anthropic, model from a saved config per agent node). No deep-dive doc yet. diff --git a/docs/wiki/domain-map.md b/docs/wiki/domain-map.md index d0099b514..2c9390a3e 100644 --- a/docs/wiki/domain-map.md +++ b/docs/wiki/domain-map.md @@ -36,11 +36,10 @@ APIKey → Organization, Project, User # programmatic access | STTSample / STTResult | stt_evaluation.py | Dataset, Run, File, Language | human annotation UI (logical) | | TTSResult | tts_evaluation.py | Run, Org, Project | human annotation UI (logical) | | Assessment / AssessmentRun | assessment.py | Config, AssessmentSubmission, BatchJob, Job, Org, Project | console UI (logical); webhook consumers (logical) | -| Document | document.py | Project, Document (parent) | DocumentCollection, DocTransformationJob, FineTuning, ModelEvaluation | +| Document | document.py | Project, Document (parent) | DocumentCollection, FineTuning, ModelEvaluation | | Collection | collection.py | Project | DocumentCollection, CollectionJob; provider vector stores (logical); rag chatbot turns search OpenAI collections by `knowledge_base_id` from the config (logical) | | DocumentCollection | document_collection.py | Document, Collection | RAG lookups (logical) | | CollectionJob | collection_job.py | Collection, Project | async collection create/delete (logical) | -| DocTransformationJob | doc_transformation_job.py | Document | doctransform service (logical) | | File | file.py | Org, Project | STT samples; object storage keys (logical) | | FineTuning | fine_tuning.py | Document, Org, Project | ModelEvaluation | | ModelEvaluation | model_evaluation.py | FineTuning, Document, Org, Project | console UI (logical) | diff --git a/docs/wiki/modules/knowledge-base.md b/docs/wiki/modules/knowledge-base.md index c8e8c465c..2eb6e9277 100644 --- a/docs/wiki/modules/knowledge-base.md +++ b/docs/wiki/modules/knowledge-base.md @@ -1,40 +1,37 @@ # Module: Knowledge Base -Documents + collections for RAG: upload documents, transform them, group into provider vector-store collections. +Documents + collections for RAG: upload documents and group them into provider vector-store collections. Document transformation (Zerox pdf→markdown) was removed; `doc_transformation_job` was dropped in migration 096. Deep dive: `docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md` (§3 upload, §5 collection lifecycle, §6 batching, §7 dedup, §8 provider abstraction, §10 deletion). All paths relative to `backend/app/`. ## Routes -- `api/routes/documents/document.py` — upload/list (v1 multipart upload, the only path that transforms); `DELETE /documents/{id}` soft-deletes the row, `DELETE /documents/{id}/permanent` removes the S3 object and the row (dependents cascade). Neither touches collections or the provider. -- `api/routes/documents/v2/document.py` — v2 pre-signed upload: `POST /documents/uploads` → 200 (issues a pre-signed POST to a pending key; nothing persisted) then `PUT /documents/{document_id}` → 201 (registers the pending object; no body); no transformation +- `api/routes/documents/document.py` — upload/list (v1 multipart upload); `DELETE /documents/{id}` soft-deletes the row, `DELETE /documents/{id}/permanent` removes the S3 object and the row (dependents cascade). Neither touches collections or the provider. +- `api/routes/documents/v2/document.py` — v2 pre-signed upload: `POST /documents/uploads` → 200 (issues a pre-signed POST to a pending key; nothing persisted) then `PUT /documents/{document_id}` → 201 (registers the pending object; no body) - `api/routes/collections.py`, `api/routes/collection_job.py` — collection CRUD + job status -- `api/routes/doc_transformation_job.py` — transform job status ## Tables (SQLModel) | Table | Model | |---|---| -| `document` (Document; self-FK parent→transformed child) | `models/document.py` | +| `document` (Document; self-FK parent→transformed child, legacy rows only) | `models/document.py` | | `collection` (Collection) | `models/collection.py` | | `document_collection` (join) | `models/document_collection.py` | | `collection_job` (CollectionJob) | `models/collection_job.py` | -| `doc_transformation_job` | `models/doc_transformation_job.py` | | `file` (File) | `models/file.py` | ## Services / CRUD - `services/collections/` — `create_collection.py`, `delete_collection.py`, `providers/`, `helpers.py` -- `services/documents/` — `helpers.py` (v1 upload path), `registration.py` (v2 upload policy: `initiate_document_upload`, `register_uploaded_document`), `validator.py`, `constants.py` (`MAX_DOC_SIZE_MB`, v2 upload limits) -- `services/doctransform/` — `job.py`, `registry.py`, `transformer.py`, `zerox_transformer.py` +- `services/documents/` — `helpers.py` (v1 upload path), `registration.py` (v2 upload policy: `initiate_document_upload`, `register_uploaded_document`), `validator.py`, `formats.py` (extension → format map), `constants.py` (`MAX_DOC_SIZE_MB`, v2 upload limits) - `crud/collection/`, `crud/document/`, `crud/document_collection.py`, `crud/rag/` (`OpenAIVectorStoreCrud`: create/read/update/delete + `search`, used by the chatbot rag agent), `crud/file.py` ## Async -- Collection create/delete and doc transforms run as Celery jobs (`collection_job`, `doc_transformation_job` track state). +- Collection create/delete run as Celery jobs (`collection_job` tracks state). ## External -- OpenAI vector stores / file uploads, object storage (`core/cloud/storage.py`), Zerox/OCR for transforms. +- OpenAI vector stores / file uploads, object storage (`core/cloud/storage.py`). ## Gotchas -- `signed_url` behaviour is chosen per request by the `download` query param (default false = inline, as before). `put()` stores the upload's `Content-Type`, so a bare presigned URL for a PDF opens in a tab (CSV/XLSX datasets happen to download, which is why only KB docs looked broken). `get_signed_url(..., filename=...)` adds `ResponseContentDisposition: attachment`; `_signed_url()` in `services/documents/helpers.py` passes `fname` only when `download` is set, and the flag threads through `build_document_schema(s)` / `build_job_schema(s)` from `api/routes/documents/document.py`, `doc_transformation_job.py` and `collections.py`. An attachment URL will not render in an `