You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

task_executor.py 33KB

Removed beartype (#3528) ### What problem does this PR solve? The beartype configuration of main(64f50992e0fc4dce73e79f8b951a02e31cb2d638) is: ``` from beartype import BeartypeConf from beartype.claw import beartype_all # <-- you didn't sign up for this beartype_all(conf=BeartypeConf(violation_type=UserWarning)) # <-- emit warnings from all code ``` ragflow_server failed at a third-party package: ``` (ragflow-py3.10) zhichyu@iris:~/github.com/infiniflow/ragflow$ rm -rf logs/* && bash docker/launch_backend_service.sh Starting task_executor.py for task 0 (Attempt 1) Starting ragflow_server.py (Attempt 1) Traceback (most recent call last): File "/home/zhichyu/github.com/infiniflow/ragflow/api/ragflow_server.py", line 22, in <module> from api.utils.log_utils import initRootLogger File "/home/zhichyu/github.com/infiniflow/ragflow/api/utils/__init__.py", line 25, in <module> import requests File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/requests/__init__.py", line 43, in <module> import urllib3 File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/__init__.py", line 15, in <module> from ._base_connection import _TYPE_BODY File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/_base_connection.py", line 5, in <module> from .util.connection import _TYPE_SOCKET_OPTIONS File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/util/__init__.py", line 4, in <module> from .connection import is_connection_dropped File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/util/connection.py", line 7, in <module> from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/util/timeout.py", line 20, in <module> _DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token NameError: name 'Final' is not defined Traceback (most recent call last): File "/home/zhichyu/github.com/infiniflow/ragflow/rag/svr/task_executor.py", line 22, in <module> from api.utils.log_utils import initRootLogger File "/home/zhichyu/github.com/infiniflow/ragflow/api/utils/__init__.py", line 25, in <module> import requests File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/requests/__init__.py", line 43, in <module> import urllib3 File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/__init__.py", line 15, in <module> from ._base_connection import _TYPE_BODY File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/_base_connection.py", line 5, in <module> from .util.connection import _TYPE_SOCKET_OPTIONS File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/util/__init__.py", line 4, in <module> from .connection import is_connection_dropped File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/util/connection.py", line 7, in <module> from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT File "/home/zhichyu/github.com/infiniflow/ragflow/.venv/lib/python3.10/site-packages/urllib3/util/timeout.py", line 20, in <module> _DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token NameError: name 'Final' is not defined ``` This third-package is out of our control. I have to remove beartype entirely. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
11 mesi fa
Feat: make document parsing and embedding batch sizes configurable via environment variables (#8266) ### Description This PR introduces two new environment variables, ‎`DOC_BULK_SIZE` and ‎`EMBEDDING_BATCH_SIZE`, to allow flexible tuning of batch sizes for document parsing and embedding vectorization in RAGFlow. By making these parameters configurable, users can optimize performance and resource usage according to their hardware capabilities and workload requirements. ### What problem does this PR solve? Previously, the batch sizes for document parsing and embedding were hardcoded, limiting the ability to adjust throughput and memory consumption. This PR enables users to set these values via environment variables (in ‎`.env`, Helm chart, or directly in the deployment environment), improving flexibility and scalability for both small and large deployments. - ‎`DOC_BULK_SIZE`: Controls how many document chunks are processed in a single batch during document parsing (default: 4). - ‎`EMBEDDING_BATCH_SIZE`: Controls how many text chunks are processed in a single batch during embedding vectorization (default: 16). This change updates the codebase, documentation, and configuration files to reflect the new options. ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [x] Documentation Update - [ ] Refactoring - [x] Performance Improvement - [ ] Other (please describe): ### Additional context - Updated ‎`.env`, ‎`helm/values.yaml`, and documentation to describe the new variables. - Modified relevant code paths to use the environment variables instead of hardcoded values. - Users can now tune these parameters to achieve better throughput or reduce memory usage as needed. Before: Default value: <img width="643" alt="image" src="https://github.com/user-attachments/assets/086e1173-18f3-419d-a0f5-68394f63866a" /> After: 10x: <img width="777" alt="image" src="https://github.com/user-attachments/assets/5722bbc0-0bcb-4536-b928-077031e550f1" />
4 mesi fa
fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106) ## Problem Description Multiple files in the RAGFlow project contain closure trap issues when using lambda functions with `trio.open_nursery()`. This problem causes concurrent tasks created in loops to reference the same variable, resulting in all tasks processing the same data (the data from the last iteration) rather than each task processing its corresponding data from the loop. ## Issue Details When using a `lambda` to create a closure function and passing it to `nursery.start_soon()` within a loop, the lambda function captures a reference to the loop variable rather than its value. For example: ```python # Problematic code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn)) ``` In this pattern, when concurrent tasks begin execution, `d` has already become the value after the loop ends (typically the last element), causing all tasks to use the same data. ## Fix Solution Changed the way concurrent tasks are created with `nursery.start_soon()` by leveraging Trio's API design to directly pass the function and its arguments separately: ```python # Fixed code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn) ``` This way, each task uses the parameter values at the time of the function call, rather than references captured through closures. ## Fixed Files Fixed closure traps in the following files: 1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword extraction, question generation, and tag processing 2. `rag/raptor.py`: 1 fix, involving document summarization 3. `graphrag/utils.py`: 2 fixes, involving graph node and edge processing 4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution and graph node merging 5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document processing 6. `graphrag/general/extractor.py`: 3 fixes, involving content processing and graph node/edge merging 7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving community report extraction ## Potential Impact This fix resolves a serious concurrency issue that could have caused: - Data processing errors (processing duplicate data) - Performance degradation (all tasks working on the same data) - Inconsistent results (some data not being processed) After the fix, all concurrent tasks should correctly process their respective data, improving system correctness and reliability.
6 mesi fa
fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106) ## Problem Description Multiple files in the RAGFlow project contain closure trap issues when using lambda functions with `trio.open_nursery()`. This problem causes concurrent tasks created in loops to reference the same variable, resulting in all tasks processing the same data (the data from the last iteration) rather than each task processing its corresponding data from the loop. ## Issue Details When using a `lambda` to create a closure function and passing it to `nursery.start_soon()` within a loop, the lambda function captures a reference to the loop variable rather than its value. For example: ```python # Problematic code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn)) ``` In this pattern, when concurrent tasks begin execution, `d` has already become the value after the loop ends (typically the last element), causing all tasks to use the same data. ## Fix Solution Changed the way concurrent tasks are created with `nursery.start_soon()` by leveraging Trio's API design to directly pass the function and its arguments separately: ```python # Fixed code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn) ``` This way, each task uses the parameter values at the time of the function call, rather than references captured through closures. ## Fixed Files Fixed closure traps in the following files: 1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword extraction, question generation, and tag processing 2. `rag/raptor.py`: 1 fix, involving document summarization 3. `graphrag/utils.py`: 2 fixes, involving graph node and edge processing 4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution and graph node merging 5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document processing 6. `graphrag/general/extractor.py`: 3 fixes, involving content processing and graph node/edge merging 7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving community report extraction ## Potential Impact This fix resolves a serious concurrency issue that could have caused: - Data processing errors (processing duplicate data) - Performance degradation (all tasks working on the same data) - Inconsistent results (some data not being processed) After the fix, all concurrent tasks should correctly process their respective data, improving system correctness and reliability.
6 mesi fa
fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106) ## Problem Description Multiple files in the RAGFlow project contain closure trap issues when using lambda functions with `trio.open_nursery()`. This problem causes concurrent tasks created in loops to reference the same variable, resulting in all tasks processing the same data (the data from the last iteration) rather than each task processing its corresponding data from the loop. ## Issue Details When using a `lambda` to create a closure function and passing it to `nursery.start_soon()` within a loop, the lambda function captures a reference to the loop variable rather than its value. For example: ```python # Problematic code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn)) ``` In this pattern, when concurrent tasks begin execution, `d` has already become the value after the loop ends (typically the last element), causing all tasks to use the same data. ## Fix Solution Changed the way concurrent tasks are created with `nursery.start_soon()` by leveraging Trio's API design to directly pass the function and its arguments separately: ```python # Fixed code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn) ``` This way, each task uses the parameter values at the time of the function call, rather than references captured through closures. ## Fixed Files Fixed closure traps in the following files: 1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword extraction, question generation, and tag processing 2. `rag/raptor.py`: 1 fix, involving document summarization 3. `graphrag/utils.py`: 2 fixes, involving graph node and edge processing 4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution and graph node merging 5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document processing 6. `graphrag/general/extractor.py`: 3 fixes, involving content processing and graph node/edge merging 7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving community report extraction ## Potential Impact This fix resolves a serious concurrency issue that could have caused: - Data processing errors (processing duplicate data) - Performance degradation (all tasks working on the same data) - Inconsistent results (some data not being processed) After the fix, all concurrent tasks should correctly process their respective data, improving system correctness and reliability.
6 mesi fa
Feat: make document parsing and embedding batch sizes configurable via environment variables (#8266) ### Description This PR introduces two new environment variables, ‎`DOC_BULK_SIZE` and ‎`EMBEDDING_BATCH_SIZE`, to allow flexible tuning of batch sizes for document parsing and embedding vectorization in RAGFlow. By making these parameters configurable, users can optimize performance and resource usage according to their hardware capabilities and workload requirements. ### What problem does this PR solve? Previously, the batch sizes for document parsing and embedding were hardcoded, limiting the ability to adjust throughput and memory consumption. This PR enables users to set these values via environment variables (in ‎`.env`, Helm chart, or directly in the deployment environment), improving flexibility and scalability for both small and large deployments. - ‎`DOC_BULK_SIZE`: Controls how many document chunks are processed in a single batch during document parsing (default: 4). - ‎`EMBEDDING_BATCH_SIZE`: Controls how many text chunks are processed in a single batch during embedding vectorization (default: 16). This change updates the codebase, documentation, and configuration files to reflect the new options. ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [x] Documentation Update - [ ] Refactoring - [x] Performance Improvement - [ ] Other (please describe): ### Additional context - Updated ‎`.env`, ‎`helm/values.yaml`, and documentation to describe the new variables. - Modified relevant code paths to use the environment variables instead of hardcoded values. - Users can now tune these parameters to achieve better throughput or reduce memory usage as needed. Before: Default value: <img width="643" alt="image" src="https://github.com/user-attachments/assets/086e1173-18f3-419d-a0f5-68394f63866a" /> After: 10x: <img width="777" alt="image" src="https://github.com/user-attachments/assets/5722bbc0-0bcb-4536-b928-077031e550f1" />
4 mesi fa
Feat: make document parsing and embedding batch sizes configurable via environment variables (#8266) ### Description This PR introduces two new environment variables, ‎`DOC_BULK_SIZE` and ‎`EMBEDDING_BATCH_SIZE`, to allow flexible tuning of batch sizes for document parsing and embedding vectorization in RAGFlow. By making these parameters configurable, users can optimize performance and resource usage according to their hardware capabilities and workload requirements. ### What problem does this PR solve? Previously, the batch sizes for document parsing and embedding were hardcoded, limiting the ability to adjust throughput and memory consumption. This PR enables users to set these values via environment variables (in ‎`.env`, Helm chart, or directly in the deployment environment), improving flexibility and scalability for both small and large deployments. - ‎`DOC_BULK_SIZE`: Controls how many document chunks are processed in a single batch during document parsing (default: 4). - ‎`EMBEDDING_BATCH_SIZE`: Controls how many text chunks are processed in a single batch during embedding vectorization (default: 16). This change updates the codebase, documentation, and configuration files to reflect the new options. ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [x] Documentation Update - [ ] Refactoring - [x] Performance Improvement - [ ] Other (please describe): ### Additional context - Updated ‎`.env`, ‎`helm/values.yaml`, and documentation to describe the new variables. - Modified relevant code paths to use the environment variables instead of hardcoded values. - Users can now tune these parameters to achieve better throughput or reduce memory usage as needed. Before: Default value: <img width="643" alt="image" src="https://github.com/user-attachments/assets/086e1173-18f3-419d-a0f5-68394f63866a" /> After: 10x: <img width="777" alt="image" src="https://github.com/user-attachments/assets/5722bbc0-0bcb-4536-b928-077031e550f1" />
4 mesi fa
Feat: make document parsing and embedding batch sizes configurable via environment variables (#8266) ### Description This PR introduces two new environment variables, ‎`DOC_BULK_SIZE` and ‎`EMBEDDING_BATCH_SIZE`, to allow flexible tuning of batch sizes for document parsing and embedding vectorization in RAGFlow. By making these parameters configurable, users can optimize performance and resource usage according to their hardware capabilities and workload requirements. ### What problem does this PR solve? Previously, the batch sizes for document parsing and embedding were hardcoded, limiting the ability to adjust throughput and memory consumption. This PR enables users to set these values via environment variables (in ‎`.env`, Helm chart, or directly in the deployment environment), improving flexibility and scalability for both small and large deployments. - ‎`DOC_BULK_SIZE`: Controls how many document chunks are processed in a single batch during document parsing (default: 4). - ‎`EMBEDDING_BATCH_SIZE`: Controls how many text chunks are processed in a single batch during embedding vectorization (default: 16). This change updates the codebase, documentation, and configuration files to reflect the new options. ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [x] Documentation Update - [ ] Refactoring - [x] Performance Improvement - [ ] Other (please describe): ### Additional context - Updated ‎`.env`, ‎`helm/values.yaml`, and documentation to describe the new variables. - Modified relevant code paths to use the environment variables instead of hardcoded values. - Users can now tune these parameters to achieve better throughput or reduce memory usage as needed. Before: Default value: <img width="643" alt="image" src="https://github.com/user-attachments/assets/086e1173-18f3-419d-a0f5-68394f63866a" /> After: 10x: <img width="777" alt="image" src="https://github.com/user-attachments/assets/5722bbc0-0bcb-4536-b928-077031e550f1" />
4 mesi fa
fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106) ## Problem Description Multiple files in the RAGFlow project contain closure trap issues when using lambda functions with `trio.open_nursery()`. This problem causes concurrent tasks created in loops to reference the same variable, resulting in all tasks processing the same data (the data from the last iteration) rather than each task processing its corresponding data from the loop. ## Issue Details When using a `lambda` to create a closure function and passing it to `nursery.start_soon()` within a loop, the lambda function captures a reference to the loop variable rather than its value. For example: ```python # Problematic code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn)) ``` In this pattern, when concurrent tasks begin execution, `d` has already become the value after the loop ends (typically the last element), causing all tasks to use the same data. ## Fix Solution Changed the way concurrent tasks are created with `nursery.start_soon()` by leveraging Trio's API design to directly pass the function and its arguments separately: ```python # Fixed code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn) ``` This way, each task uses the parameter values at the time of the function call, rather than references captured through closures. ## Fixed Files Fixed closure traps in the following files: 1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword extraction, question generation, and tag processing 2. `rag/raptor.py`: 1 fix, involving document summarization 3. `graphrag/utils.py`: 2 fixes, involving graph node and edge processing 4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution and graph node merging 5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document processing 6. `graphrag/general/extractor.py`: 3 fixes, involving content processing and graph node/edge merging 7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving community report extraction ## Potential Impact This fix resolves a serious concurrency issue that could have caused: - Data processing errors (processing duplicate data) - Performance degradation (all tasks working on the same data) - Inconsistent results (some data not being processed) After the fix, all concurrent tasks should correctly process their respective data, improving system correctness and reliability.
6 mesi fa
fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106) ## Problem Description Multiple files in the RAGFlow project contain closure trap issues when using lambda functions with `trio.open_nursery()`. This problem causes concurrent tasks created in loops to reference the same variable, resulting in all tasks processing the same data (the data from the last iteration) rather than each task processing its corresponding data from the loop. ## Issue Details When using a `lambda` to create a closure function and passing it to `nursery.start_soon()` within a loop, the lambda function captures a reference to the loop variable rather than its value. For example: ```python # Problematic code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn)) ``` In this pattern, when concurrent tasks begin execution, `d` has already become the value after the loop ends (typically the last element), causing all tasks to use the same data. ## Fix Solution Changed the way concurrent tasks are created with `nursery.start_soon()` by leveraging Trio's API design to directly pass the function and its arguments separately: ```python # Fixed code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn) ``` This way, each task uses the parameter values at the time of the function call, rather than references captured through closures. ## Fixed Files Fixed closure traps in the following files: 1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword extraction, question generation, and tag processing 2. `rag/raptor.py`: 1 fix, involving document summarization 3. `graphrag/utils.py`: 2 fixes, involving graph node and edge processing 4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution and graph node merging 5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document processing 6. `graphrag/general/extractor.py`: 3 fixes, involving content processing and graph node/edge merging 7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving community report extraction ## Potential Impact This fix resolves a serious concurrency issue that could have caused: - Data processing errors (processing duplicate data) - Performance degradation (all tasks working on the same data) - Inconsistent results (some data not being processed) After the fix, all concurrent tasks should correctly process their respective data, improving system correctness and reliability.
6 mesi fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # from beartype import BeartypeConf
  16. # from beartype.claw import beartype_all # <-- you didn't sign up for this
  17. # beartype_all(conf=BeartypeConf(violation_type=UserWarning)) # <-- emit warnings from all code
  18. import random
  19. import sys
  20. import threading
  21. import time
  22. from api.utils.log_utils import initRootLogger, get_project_base_directory
  23. from graphrag.general.index import run_graphrag
  24. from graphrag.utils import get_llm_cache, set_llm_cache, get_tags_from_cache, set_tags_to_cache
  25. from rag.prompts import keyword_extraction, question_proposal, content_tagging
  26. import logging
  27. import os
  28. from datetime import datetime
  29. import json
  30. import xxhash
  31. import copy
  32. import re
  33. from functools import partial
  34. from io import BytesIO
  35. from multiprocessing.context import TimeoutError
  36. from timeit import default_timer as timer
  37. import tracemalloc
  38. import signal
  39. import trio
  40. import exceptiongroup
  41. import faulthandler
  42. import numpy as np
  43. from peewee import DoesNotExist
  44. from api.db import LLMType, ParserType, TaskStatus
  45. from api.db.services.document_service import DocumentService
  46. from api.db.services.llm_service import LLMBundle
  47. from api.db.services.task_service import TaskService
  48. from api.db.services.file2document_service import File2DocumentService
  49. from api import settings
  50. from api.versions import get_ragflow_version
  51. from api.db.db_models import close_connection
  52. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one, audio, \
  53. email, tag
  54. from rag.nlp import search, rag_tokenizer
  55. from rag.raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
  56. from rag.settings import DOC_MAXIMUM_SIZE, DOC_BULK_SIZE, EMBEDDING_BATCH_SIZE, SVR_CONSUMER_GROUP_NAME, get_svr_queue_name, get_svr_queue_names, print_rag_settings, TAG_FLD, PAGERANK_FLD
  57. from rag.utils import num_tokens_from_string, truncate
  58. from rag.utils.redis_conn import REDIS_CONN, RedisDistributedLock
  59. from rag.utils.storage_factory import STORAGE_IMPL
  60. from graphrag.utils import chat_limiter
  61. BATCH_SIZE = 64
  62. FACTORY = {
  63. "general": naive,
  64. ParserType.NAIVE.value: naive,
  65. ParserType.PAPER.value: paper,
  66. ParserType.BOOK.value: book,
  67. ParserType.PRESENTATION.value: presentation,
  68. ParserType.MANUAL.value: manual,
  69. ParserType.LAWS.value: laws,
  70. ParserType.QA.value: qa,
  71. ParserType.TABLE.value: table,
  72. ParserType.RESUME.value: resume,
  73. ParserType.PICTURE.value: picture,
  74. ParserType.ONE.value: one,
  75. ParserType.AUDIO.value: audio,
  76. ParserType.EMAIL.value: email,
  77. ParserType.KG.value: naive,
  78. ParserType.TAG.value: tag
  79. }
  80. UNACKED_ITERATOR = None
  81. CONSUMER_NO = "0" if len(sys.argv) < 2 else sys.argv[1]
  82. CONSUMER_NAME = "task_executor_" + CONSUMER_NO
  83. BOOT_AT = datetime.now().astimezone().isoformat(timespec="milliseconds")
  84. PENDING_TASKS = 0
  85. LAG_TASKS = 0
  86. DONE_TASKS = 0
  87. FAILED_TASKS = 0
  88. CURRENT_TASKS = {}
  89. MAX_CONCURRENT_TASKS = int(os.environ.get('MAX_CONCURRENT_TASKS', "5"))
  90. MAX_CONCURRENT_CHUNK_BUILDERS = int(os.environ.get('MAX_CONCURRENT_CHUNK_BUILDERS', "1"))
  91. MAX_CONCURRENT_MINIO = int(os.environ.get('MAX_CONCURRENT_MINIO', '10'))
  92. task_limiter = trio.Semaphore(MAX_CONCURRENT_TASKS)
  93. chunk_limiter = trio.CapacityLimiter(MAX_CONCURRENT_CHUNK_BUILDERS)
  94. minio_limiter = trio.CapacityLimiter(MAX_CONCURRENT_MINIO)
  95. kg_limiter = trio.CapacityLimiter(2)
  96. WORKER_HEARTBEAT_TIMEOUT = int(os.environ.get('WORKER_HEARTBEAT_TIMEOUT', '120'))
  97. stop_event = threading.Event()
  98. def signal_handler(sig, frame):
  99. logging.info("Received interrupt signal, shutting down...")
  100. stop_event.set()
  101. time.sleep(1)
  102. sys.exit(0)
  103. # SIGUSR1 handler: start tracemalloc and take snapshot
  104. def start_tracemalloc_and_snapshot(signum, frame):
  105. if not tracemalloc.is_tracing():
  106. logging.info("start tracemalloc")
  107. tracemalloc.start()
  108. else:
  109. logging.info("tracemalloc is already running")
  110. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  111. snapshot_file = f"snapshot_{timestamp}.trace"
  112. snapshot_file = os.path.abspath(os.path.join(get_project_base_directory(), "logs", f"{os.getpid()}_snapshot_{timestamp}.trace"))
  113. snapshot = tracemalloc.take_snapshot()
  114. snapshot.dump(snapshot_file)
  115. current, peak = tracemalloc.get_traced_memory()
  116. if sys.platform == "win32":
  117. import psutil
  118. process = psutil.Process()
  119. max_rss = process.memory_info().rss / 1024
  120. else:
  121. import resource
  122. max_rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
  123. logging.info(f"taken snapshot {snapshot_file}. max RSS={max_rss / 1000:.2f} MB, current memory usage: {current / 10**6:.2f} MB, Peak memory usage: {peak / 10**6:.2f} MB")
  124. # SIGUSR2 handler: stop tracemalloc
  125. def stop_tracemalloc(signum, frame):
  126. if tracemalloc.is_tracing():
  127. logging.info("stop tracemalloc")
  128. tracemalloc.stop()
  129. else:
  130. logging.info("tracemalloc not running")
  131. class TaskCanceledException(Exception):
  132. def __init__(self, msg):
  133. self.msg = msg
  134. def set_progress(task_id, from_page=0, to_page=-1, prog=None, msg="Processing..."):
  135. try:
  136. if prog is not None and prog < 0:
  137. msg = "[ERROR]" + msg
  138. cancel = TaskService.do_cancel(task_id)
  139. if cancel:
  140. msg += " [Canceled]"
  141. prog = -1
  142. if to_page > 0:
  143. if msg:
  144. if from_page < to_page:
  145. msg = f"Page({from_page + 1}~{to_page + 1}): " + msg
  146. if msg:
  147. msg = datetime.now().strftime("%H:%M:%S") + " " + msg
  148. d = {"progress_msg": msg}
  149. if prog is not None:
  150. d["progress"] = prog
  151. TaskService.update_progress(task_id, d)
  152. close_connection()
  153. if cancel:
  154. raise TaskCanceledException(msg)
  155. logging.info(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}")
  156. except DoesNotExist:
  157. logging.warning(f"set_progress({task_id}) got exception DoesNotExist")
  158. except Exception:
  159. logging.exception(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}, got exception")
  160. async def collect():
  161. global CONSUMER_NAME, DONE_TASKS, FAILED_TASKS
  162. global UNACKED_ITERATOR
  163. svr_queue_names = get_svr_queue_names()
  164. try:
  165. if not UNACKED_ITERATOR:
  166. UNACKED_ITERATOR = REDIS_CONN.get_unacked_iterator(svr_queue_names, SVR_CONSUMER_GROUP_NAME, CONSUMER_NAME)
  167. try:
  168. redis_msg = next(UNACKED_ITERATOR)
  169. except StopIteration:
  170. for svr_queue_name in svr_queue_names:
  171. redis_msg = REDIS_CONN.queue_consumer(svr_queue_name, SVR_CONSUMER_GROUP_NAME, CONSUMER_NAME)
  172. if redis_msg:
  173. break
  174. except Exception:
  175. logging.exception("collect got exception")
  176. return None, None
  177. if not redis_msg:
  178. return None, None
  179. msg = redis_msg.get_message()
  180. if not msg:
  181. logging.error(f"collect got empty message of {redis_msg.get_msg_id()}")
  182. redis_msg.ack()
  183. return None, None
  184. canceled = False
  185. task = TaskService.get_task(msg["id"])
  186. if task:
  187. _, doc = DocumentService.get_by_id(task["doc_id"])
  188. canceled = doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  189. if not task or canceled:
  190. state = "is unknown" if not task else "has been cancelled"
  191. FAILED_TASKS += 1
  192. logging.warning(f"collect task {msg['id']} {state}")
  193. redis_msg.ack()
  194. return None, None
  195. task["task_type"] = msg.get("task_type", "")
  196. return redis_msg, task
  197. async def get_storage_binary(bucket, name):
  198. return await trio.to_thread.run_sync(lambda: STORAGE_IMPL.get(bucket, name))
  199. async def build_chunks(task, progress_callback):
  200. if task["size"] > DOC_MAXIMUM_SIZE:
  201. set_progress(task["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  202. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  203. return []
  204. chunker = FACTORY[task["parser_id"].lower()]
  205. try:
  206. st = timer()
  207. bucket, name = File2DocumentService.get_storage_address(doc_id=task["doc_id"])
  208. binary = await get_storage_binary(bucket, name)
  209. logging.info("From minio({}) {}/{}".format(timer() - st, task["location"], task["name"]))
  210. except TimeoutError:
  211. progress_callback(-1, "Internal server error: Fetch file from minio timeout. Could you try it again.")
  212. logging.exception(
  213. "Minio {}/{} got timeout: Fetch file from minio timeout.".format(task["location"], task["name"]))
  214. raise
  215. except Exception as e:
  216. if re.search("(No such file|not found)", str(e)):
  217. progress_callback(-1, "Can not find file <%s> from minio. Could you try it again?" % task["name"])
  218. else:
  219. progress_callback(-1, "Get file from minio: %s" % str(e).replace("'", ""))
  220. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  221. raise
  222. try:
  223. async with chunk_limiter:
  224. cks = await trio.to_thread.run_sync(lambda: chunker.chunk(task["name"], binary=binary, from_page=task["from_page"],
  225. to_page=task["to_page"], lang=task["language"], callback=progress_callback,
  226. kb_id=task["kb_id"], parser_config=task["parser_config"], tenant_id=task["tenant_id"]))
  227. logging.info("Chunking({}) {}/{} done".format(timer() - st, task["location"], task["name"]))
  228. except TaskCanceledException:
  229. raise
  230. except Exception as e:
  231. progress_callback(-1, "Internal server error while chunking: %s" % str(e).replace("'", ""))
  232. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  233. raise
  234. docs = []
  235. doc = {
  236. "doc_id": task["doc_id"],
  237. "kb_id": str(task["kb_id"])
  238. }
  239. if task["pagerank"]:
  240. doc[PAGERANK_FLD] = int(task["pagerank"])
  241. st = timer()
  242. async def upload_to_minio(document, chunk):
  243. try:
  244. d = copy.deepcopy(document)
  245. d.update(chunk)
  246. d["id"] = xxhash.xxh64((chunk["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
  247. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  248. d["create_timestamp_flt"] = datetime.now().timestamp()
  249. if not d.get("image"):
  250. _ = d.pop("image", None)
  251. d["img_id"] = ""
  252. docs.append(d)
  253. return
  254. output_buffer = BytesIO()
  255. if isinstance(d["image"], bytes):
  256. output_buffer = BytesIO(d["image"])
  257. else:
  258. d["image"].save(output_buffer, format='JPEG')
  259. async with minio_limiter:
  260. await trio.to_thread.run_sync(lambda: STORAGE_IMPL.put(task["kb_id"], d["id"], output_buffer.getvalue()))
  261. d["img_id"] = "{}-{}".format(task["kb_id"], d["id"])
  262. del d["image"]
  263. docs.append(d)
  264. except Exception:
  265. logging.exception(
  266. "Saving image of chunk {}/{}/{} got exception".format(task["location"], task["name"], d["id"]))
  267. raise
  268. async with trio.open_nursery() as nursery:
  269. for ck in cks:
  270. nursery.start_soon(upload_to_minio, doc, ck)
  271. el = timer() - st
  272. logging.info("MINIO PUT({}) cost {:.3f} s".format(task["name"], el))
  273. if task["parser_config"].get("auto_keywords", 0):
  274. st = timer()
  275. progress_callback(msg="Start to generate keywords for every chunk ...")
  276. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  277. async def doc_keyword_extraction(chat_mdl, d, topn):
  278. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "keywords", {"topn": topn})
  279. if not cached:
  280. async with chat_limiter:
  281. cached = await trio.to_thread.run_sync(lambda: keyword_extraction(chat_mdl, d["content_with_weight"], topn))
  282. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "keywords", {"topn": topn})
  283. if cached:
  284. d["important_kwd"] = cached.split(",")
  285. d["important_tks"] = rag_tokenizer.tokenize(" ".join(d["important_kwd"]))
  286. return
  287. async with trio.open_nursery() as nursery:
  288. for d in docs:
  289. nursery.start_soon(doc_keyword_extraction, chat_mdl, d, task["parser_config"]["auto_keywords"])
  290. progress_callback(msg="Keywords generation {} chunks completed in {:.2f}s".format(len(docs), timer() - st))
  291. if task["parser_config"].get("auto_questions", 0):
  292. st = timer()
  293. progress_callback(msg="Start to generate questions for every chunk ...")
  294. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  295. async def doc_question_proposal(chat_mdl, d, topn):
  296. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "question", {"topn": topn})
  297. if not cached:
  298. async with chat_limiter:
  299. cached = await trio.to_thread.run_sync(lambda: question_proposal(chat_mdl, d["content_with_weight"], topn))
  300. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "question", {"topn": topn})
  301. if cached:
  302. d["question_kwd"] = cached.split("\n")
  303. d["question_tks"] = rag_tokenizer.tokenize("\n".join(d["question_kwd"]))
  304. async with trio.open_nursery() as nursery:
  305. for d in docs:
  306. nursery.start_soon(doc_question_proposal, chat_mdl, d, task["parser_config"]["auto_questions"])
  307. progress_callback(msg="Question generation {} chunks completed in {:.2f}s".format(len(docs), timer() - st))
  308. if task["kb_parser_config"].get("tag_kb_ids", []):
  309. progress_callback(msg="Start to tag for every chunk ...")
  310. kb_ids = task["kb_parser_config"]["tag_kb_ids"]
  311. tenant_id = task["tenant_id"]
  312. topn_tags = task["kb_parser_config"].get("topn_tags", 3)
  313. S = 1000
  314. st = timer()
  315. examples = []
  316. all_tags = get_tags_from_cache(kb_ids)
  317. if not all_tags:
  318. all_tags = settings.retrievaler.all_tags_in_portion(tenant_id, kb_ids, S)
  319. set_tags_to_cache(kb_ids, all_tags)
  320. else:
  321. all_tags = json.loads(all_tags)
  322. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  323. docs_to_tag = []
  324. for d in docs:
  325. task_canceled = TaskService.do_cancel(task["id"])
  326. if task_canceled:
  327. progress_callback(-1, msg="Task has been canceled.")
  328. return
  329. if settings.retrievaler.tag_content(tenant_id, kb_ids, d, all_tags, topn_tags=topn_tags, S=S) and len(d[TAG_FLD]) > 0:
  330. examples.append({"content": d["content_with_weight"], TAG_FLD: d[TAG_FLD]})
  331. else:
  332. docs_to_tag.append(d)
  333. async def doc_content_tagging(chat_mdl, d, topn_tags):
  334. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], all_tags, {"topn": topn_tags})
  335. if not cached:
  336. picked_examples = random.choices(examples, k=2) if len(examples)>2 else examples
  337. if not picked_examples:
  338. picked_examples.append({"content": "This is an example", TAG_FLD: {'example': 1}})
  339. async with chat_limiter:
  340. cached = await trio.to_thread.run_sync(lambda: content_tagging(chat_mdl, d["content_with_weight"], all_tags, picked_examples, topn=topn_tags))
  341. if cached:
  342. cached = json.dumps(cached)
  343. if cached:
  344. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, all_tags, {"topn": topn_tags})
  345. d[TAG_FLD] = json.loads(cached)
  346. async with trio.open_nursery() as nursery:
  347. for d in docs_to_tag:
  348. nursery.start_soon(doc_content_tagging, chat_mdl, d, topn_tags)
  349. progress_callback(msg="Tagging {} chunks completed in {:.2f}s".format(len(docs), timer() - st))
  350. return docs
  351. def init_kb(row, vector_size: int):
  352. idxnm = search.index_name(row["tenant_id"])
  353. return settings.docStoreConn.createIdx(idxnm, row.get("kb_id", ""), vector_size)
  354. async def embedding(docs, mdl, parser_config=None, callback=None):
  355. if parser_config is None:
  356. parser_config = {}
  357. tts, cnts = [], []
  358. for d in docs:
  359. tts.append(d.get("docnm_kwd", "Title"))
  360. c = "\n".join(d.get("question_kwd", []))
  361. if not c:
  362. c = d["content_with_weight"]
  363. c = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", c)
  364. if not c:
  365. c = "None"
  366. cnts.append(c)
  367. tk_count = 0
  368. if len(tts) == len(cnts):
  369. vts, c = await trio.to_thread.run_sync(lambda: mdl.encode(tts[0: 1]))
  370. tts = np.concatenate([vts for _ in range(len(tts))], axis=0)
  371. tk_count += c
  372. cnts_ = np.array([])
  373. for i in range(0, len(cnts), EMBEDDING_BATCH_SIZE):
  374. vts, c = await trio.to_thread.run_sync(lambda: mdl.encode([truncate(c, mdl.max_length-10) for c in cnts[i: i + EMBEDDING_BATCH_SIZE]]))
  375. if len(cnts_) == 0:
  376. cnts_ = vts
  377. else:
  378. cnts_ = np.concatenate((cnts_, vts), axis=0)
  379. tk_count += c
  380. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  381. cnts = cnts_
  382. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  383. vects = (title_w * tts + (1 - title_w) *
  384. cnts) if len(tts) == len(cnts) else cnts
  385. assert len(vects) == len(docs)
  386. vector_size = 0
  387. for i, d in enumerate(docs):
  388. v = vects[i].tolist()
  389. vector_size = len(v)
  390. d["q_%d_vec" % len(v)] = v
  391. return tk_count, vector_size
  392. async def run_raptor(row, chat_mdl, embd_mdl, vector_size, callback=None):
  393. chunks = []
  394. vctr_nm = "q_%d_vec"%vector_size
  395. for d in settings.retrievaler.chunk_list(row["doc_id"], row["tenant_id"], [str(row["kb_id"])],
  396. fields=["content_with_weight", vctr_nm]):
  397. chunks.append((d["content_with_weight"], np.array(d[vctr_nm])))
  398. raptor = Raptor(
  399. row["parser_config"]["raptor"].get("max_cluster", 64),
  400. chat_mdl,
  401. embd_mdl,
  402. row["parser_config"]["raptor"]["prompt"],
  403. row["parser_config"]["raptor"]["max_token"],
  404. row["parser_config"]["raptor"]["threshold"]
  405. )
  406. original_length = len(chunks)
  407. chunks = await raptor(chunks, row["parser_config"]["raptor"]["random_seed"], callback)
  408. doc = {
  409. "doc_id": row["doc_id"],
  410. "kb_id": [str(row["kb_id"])],
  411. "docnm_kwd": row["name"],
  412. "title_tks": rag_tokenizer.tokenize(row["name"])
  413. }
  414. if row["pagerank"]:
  415. doc[PAGERANK_FLD] = int(row["pagerank"])
  416. res = []
  417. tk_count = 0
  418. for content, vctr in chunks[original_length:]:
  419. d = copy.deepcopy(doc)
  420. d["id"] = xxhash.xxh64((content + str(d["doc_id"])).encode("utf-8")).hexdigest()
  421. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  422. d["create_timestamp_flt"] = datetime.now().timestamp()
  423. d[vctr_nm] = vctr.tolist()
  424. d["content_with_weight"] = content
  425. d["content_ltks"] = rag_tokenizer.tokenize(content)
  426. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  427. res.append(d)
  428. tk_count += num_tokens_from_string(content)
  429. return res, tk_count
  430. async def do_handle_task(task):
  431. task_id = task["id"]
  432. task_from_page = task["from_page"]
  433. task_to_page = task["to_page"]
  434. task_tenant_id = task["tenant_id"]
  435. task_embedding_id = task["embd_id"]
  436. task_language = task["language"]
  437. task_llm_id = task["llm_id"]
  438. task_dataset_id = task["kb_id"]
  439. task_doc_id = task["doc_id"]
  440. task_document_name = task["name"]
  441. task_parser_config = task["parser_config"]
  442. task_start_ts = timer()
  443. # prepare the progress callback function
  444. progress_callback = partial(set_progress, task_id, task_from_page, task_to_page)
  445. # FIXME: workaround, Infinity doesn't support table parsing method, this check is to notify user
  446. lower_case_doc_engine = settings.DOC_ENGINE.lower()
  447. if lower_case_doc_engine == 'infinity' and task['parser_id'].lower() == 'table':
  448. error_message = "Table parsing method is not supported by Infinity, please use other parsing methods or use Elasticsearch as the document engine."
  449. progress_callback(-1, msg=error_message)
  450. raise Exception(error_message)
  451. task_canceled = TaskService.do_cancel(task_id)
  452. if task_canceled:
  453. progress_callback(-1, msg="Task has been canceled.")
  454. return
  455. try:
  456. # bind embedding model
  457. embedding_model = LLMBundle(task_tenant_id, LLMType.EMBEDDING, llm_name=task_embedding_id, lang=task_language)
  458. vts, _ = embedding_model.encode(["ok"])
  459. vector_size = len(vts[0])
  460. except Exception as e:
  461. error_message = f'Fail to bind embedding model: {str(e)}'
  462. progress_callback(-1, msg=error_message)
  463. logging.exception(error_message)
  464. raise
  465. init_kb(task, vector_size)
  466. # Either using RAPTOR or Standard chunking methods
  467. if task.get("task_type", "") == "raptor":
  468. # bind LLM for raptor
  469. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  470. # run RAPTOR
  471. async with kg_limiter:
  472. chunks, token_count = await run_raptor(task, chat_model, embedding_model, vector_size, progress_callback)
  473. # Either using graphrag or Standard chunking methods
  474. elif task.get("task_type", "") == "graphrag":
  475. if not task_parser_config.get("graphrag", {}).get("use_graphrag", False):
  476. return
  477. graphrag_conf = task["kb_parser_config"].get("graphrag", {})
  478. start_ts = timer()
  479. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  480. with_resolution = graphrag_conf.get("resolution", False)
  481. with_community = graphrag_conf.get("community", False)
  482. async with kg_limiter:
  483. await run_graphrag(task, task_language, with_resolution, with_community, chat_model, embedding_model, progress_callback)
  484. progress_callback(prog=1.0, msg="Knowledge Graph done ({:.2f}s)".format(timer() - start_ts))
  485. return
  486. else:
  487. # Standard chunking methods
  488. start_ts = timer()
  489. chunks = await build_chunks(task, progress_callback)
  490. logging.info("Build document {}: {:.2f}s".format(task_document_name, timer() - start_ts))
  491. if chunks is None:
  492. return
  493. if not chunks:
  494. progress_callback(1., msg=f"No chunk built from {task_document_name}")
  495. return
  496. # TODO: exception handler
  497. ## set_progress(task["did"], -1, "ERROR: ")
  498. progress_callback(msg="Generate {} chunks".format(len(chunks)))
  499. start_ts = timer()
  500. try:
  501. token_count, vector_size = await embedding(chunks, embedding_model, task_parser_config, progress_callback)
  502. except Exception as e:
  503. error_message = "Generate embedding error:{}".format(str(e))
  504. progress_callback(-1, error_message)
  505. logging.exception(error_message)
  506. token_count = 0
  507. raise
  508. progress_message = "Embedding chunks ({:.2f}s)".format(timer() - start_ts)
  509. logging.info(progress_message)
  510. progress_callback(msg=progress_message)
  511. chunk_count = len(set([chunk["id"] for chunk in chunks]))
  512. start_ts = timer()
  513. doc_store_result = ""
  514. async def delete_image(kb_id, chunk_id):
  515. try:
  516. async with minio_limiter:
  517. STORAGE_IMPL.delete(kb_id, chunk_id)
  518. except Exception:
  519. logging.exception(
  520. "Deleting image of chunk {}/{}/{} got exception".format(task["location"], task["name"], chunk_id))
  521. raise
  522. for b in range(0, len(chunks), DOC_BULK_SIZE):
  523. doc_store_result = await trio.to_thread.run_sync(lambda: settings.docStoreConn.insert(chunks[b:b + DOC_BULK_SIZE], search.index_name(task_tenant_id), task_dataset_id))
  524. task_canceled = TaskService.do_cancel(task_id)
  525. if task_canceled:
  526. progress_callback(-1, msg="Task has been canceled.")
  527. return
  528. if b % 128 == 0:
  529. progress_callback(prog=0.8 + 0.1 * (b + 1) / len(chunks), msg="")
  530. if doc_store_result:
  531. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  532. progress_callback(-1, msg=error_message)
  533. raise Exception(error_message)
  534. chunk_ids = [chunk["id"] for chunk in chunks[:b + DOC_BULK_SIZE]]
  535. chunk_ids_str = " ".join(chunk_ids)
  536. try:
  537. TaskService.update_chunk_ids(task["id"], chunk_ids_str)
  538. except DoesNotExist:
  539. logging.warning(f"do_handle_task update_chunk_ids failed since task {task['id']} is unknown.")
  540. doc_store_result = await trio.to_thread.run_sync(lambda: settings.docStoreConn.delete({"id": chunk_ids}, search.index_name(task_tenant_id), task_dataset_id))
  541. async with trio.open_nursery() as nursery:
  542. for chunk_id in chunk_ids:
  543. nursery.start_soon(delete_image, task_dataset_id, chunk_id)
  544. return
  545. logging.info("Indexing doc({}), page({}-{}), chunks({}), elapsed: {:.2f}".format(task_document_name, task_from_page,
  546. task_to_page, len(chunks),
  547. timer() - start_ts))
  548. DocumentService.increment_chunk_num(task_doc_id, task_dataset_id, token_count, chunk_count, 0)
  549. time_cost = timer() - start_ts
  550. task_time_cost = timer() - task_start_ts
  551. progress_callback(prog=1.0, msg="Indexing done ({:.2f}s). Task done ({:.2f}s)".format(time_cost, task_time_cost))
  552. logging.info(
  553. "Chunk doc({}), page({}-{}), chunks({}), token({}), elapsed:{:.2f}".format(task_document_name, task_from_page,
  554. task_to_page, len(chunks),
  555. token_count, task_time_cost))
  556. async def handle_task():
  557. global DONE_TASKS, FAILED_TASKS
  558. redis_msg, task = await collect()
  559. if not task:
  560. await trio.sleep(5)
  561. return
  562. try:
  563. logging.info(f"handle_task begin for task {json.dumps(task)}")
  564. CURRENT_TASKS[task["id"]] = copy.deepcopy(task)
  565. await do_handle_task(task)
  566. DONE_TASKS += 1
  567. CURRENT_TASKS.pop(task["id"], None)
  568. logging.info(f"handle_task done for task {json.dumps(task)}")
  569. except Exception as e:
  570. FAILED_TASKS += 1
  571. CURRENT_TASKS.pop(task["id"], None)
  572. try:
  573. err_msg = str(e)
  574. while isinstance(e, exceptiongroup.ExceptionGroup):
  575. e = e.exceptions[0]
  576. err_msg += ' -- ' + str(e)
  577. set_progress(task["id"], prog=-1, msg=f"[Exception]: {err_msg}")
  578. except Exception:
  579. pass
  580. logging.exception(f"handle_task got exception for task {json.dumps(task)}")
  581. redis_msg.ack()
  582. async def report_status():
  583. global CONSUMER_NAME, BOOT_AT, PENDING_TASKS, LAG_TASKS, DONE_TASKS, FAILED_TASKS
  584. REDIS_CONN.sadd("TASKEXE", CONSUMER_NAME)
  585. redis_lock = RedisDistributedLock("clean_task_executor", lock_value=CONSUMER_NAME, timeout=60)
  586. while True:
  587. try:
  588. now = datetime.now()
  589. group_info = REDIS_CONN.queue_info(get_svr_queue_name(0), SVR_CONSUMER_GROUP_NAME)
  590. if group_info is not None:
  591. PENDING_TASKS = int(group_info.get("pending", 0))
  592. LAG_TASKS = int(group_info.get("lag", 0))
  593. current = copy.deepcopy(CURRENT_TASKS)
  594. heartbeat = json.dumps({
  595. "name": CONSUMER_NAME,
  596. "now": now.astimezone().isoformat(timespec="milliseconds"),
  597. "boot_at": BOOT_AT,
  598. "pending": PENDING_TASKS,
  599. "lag": LAG_TASKS,
  600. "done": DONE_TASKS,
  601. "failed": FAILED_TASKS,
  602. "current": current,
  603. })
  604. REDIS_CONN.zadd(CONSUMER_NAME, heartbeat, now.timestamp())
  605. logging.info(f"{CONSUMER_NAME} reported heartbeat: {heartbeat}")
  606. expired = REDIS_CONN.zcount(CONSUMER_NAME, 0, now.timestamp() - 60 * 30)
  607. if expired > 0:
  608. REDIS_CONN.zpopmin(CONSUMER_NAME, expired)
  609. # clean task executor
  610. if redis_lock.acquire():
  611. task_executors = REDIS_CONN.smembers("TASKEXE")
  612. for consumer_name in task_executors:
  613. if consumer_name == CONSUMER_NAME:
  614. continue
  615. expired = REDIS_CONN.zcount(
  616. consumer_name, now.timestamp() - WORKER_HEARTBEAT_TIMEOUT, now.timestamp() + 10
  617. )
  618. if expired == 0:
  619. logging.info(f"{consumer_name} expired, removed")
  620. REDIS_CONN.srem("TASKEXE", consumer_name)
  621. REDIS_CONN.delete(consumer_name)
  622. except Exception:
  623. logging.exception("report_status got exception")
  624. finally:
  625. redis_lock.release()
  626. await trio.sleep(30)
  627. def recover_pending_tasks():
  628. redis_lock = RedisDistributedLock("recover_pending_tasks", lock_value=CONSUMER_NAME, timeout=60)
  629. svr_queue_names = get_svr_queue_names()
  630. while not stop_event.is_set():
  631. try:
  632. if redis_lock.acquire():
  633. for queue_name in svr_queue_names:
  634. msgs = REDIS_CONN.get_pending_msg(queue=queue_name, group_name=SVR_CONSUMER_GROUP_NAME)
  635. msgs = [msg for msg in msgs if msg['consumer'] != CONSUMER_NAME]
  636. if len(msgs) == 0:
  637. continue
  638. task_executors = REDIS_CONN.smembers("TASKEXE")
  639. task_executor_set = {t for t in task_executors}
  640. msgs = [msg for msg in msgs if msg['consumer'] not in task_executor_set]
  641. for msg in msgs:
  642. logging.info(
  643. f"Recover pending task: {msg['message_id']}, consumer: {msg['consumer']}, "
  644. f"time since delivered: {msg['time_since_delivered'] / 1000} s"
  645. )
  646. REDIS_CONN.requeue_msg(queue_name, SVR_CONSUMER_GROUP_NAME, msg['message_id'])
  647. except Exception:
  648. logging.warning("recover_pending_tasks got exception")
  649. finally:
  650. redis_lock.release()
  651. stop_event.wait(60)
  652. async def task_manager():
  653. try:
  654. await handle_task()
  655. finally:
  656. task_limiter.release()
  657. async def main():
  658. logging.info(r"""
  659. ______ __ ______ __
  660. /_ __/___ ______/ /__ / ____/ _____ _______ __/ /_____ _____
  661. / / / __ `/ ___/ //_/ / __/ | |/_/ _ \/ ___/ / / / __/ __ \/ ___/
  662. / / / /_/ (__ ) ,< / /____> </ __/ /__/ /_/ / /_/ /_/ / /
  663. /_/ \__,_/____/_/|_| /_____/_/|_|\___/\___/\__,_/\__/\____/_/
  664. """)
  665. logging.info(f'TaskExecutor: RAGFlow version: {get_ragflow_version()}')
  666. settings.init_settings()
  667. print_rag_settings()
  668. if sys.platform != "win32":
  669. signal.signal(signal.SIGUSR1, start_tracemalloc_and_snapshot)
  670. signal.signal(signal.SIGUSR2, stop_tracemalloc)
  671. TRACE_MALLOC_ENABLED = int(os.environ.get('TRACE_MALLOC_ENABLED', "0"))
  672. if TRACE_MALLOC_ENABLED:
  673. start_tracemalloc_and_snapshot(None, None)
  674. signal.signal(signal.SIGINT, signal_handler)
  675. signal.signal(signal.SIGTERM, signal_handler)
  676. threading.Thread(name="RecoverPendingTask", target=recover_pending_tasks).start()
  677. async with trio.open_nursery() as nursery:
  678. nursery.start_soon(report_status)
  679. while not stop_event.is_set():
  680. await task_limiter.acquire()
  681. nursery.start_soon(task_manager)
  682. logging.error("BUG!!! You should not reach here!!!")
  683. if __name__ == "__main__":
  684. faulthandler.enable()
  685. initRootLogger(CONSUMER_NAME)
  686. trio.run(main)