2024-01-15 08:46:22 +08:00
|
|
|
#
|
2024-01-19 19:51:57 +08:00
|
|
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
2024-01-15 08:46:22 +08:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
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)
2024-11-20 17:43:16 +08:00
|
|
|
|
|
|
|
# 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
|
2025-01-09 17:07:21 +08:00
|
|
|
import random
|
2024-11-15 14:43:55 +08:00
|
|
|
import sys
|
2025-04-19 16:18:51 +08:00
|
|
|
import threading
|
|
|
|
import time
|
2025-03-03 10:26:45 +08:00
|
|
|
|
2025-06-18 09:41:09 +08:00
|
|
|
from api.utils.log_utils import init_root_logger, get_project_base_directory
|
2025-03-10 15:15:06 +08:00
|
|
|
from graphrag.general.index import run_graphrag
|
2025-01-09 17:07:21 +08:00
|
|
|
from graphrag.utils import get_llm_cache, set_llm_cache, get_tags_from_cache, set_tags_to_cache
|
2025-02-26 15:40:52 +08:00
|
|
|
from rag.prompts import keyword_extraction, question_proposal, content_tagging
|
2024-12-17 09:48:03 +08:00
|
|
|
|
2024-12-10 09:36:59 +08:00
|
|
|
import logging
|
|
|
|
import os
|
2024-11-15 14:43:55 +08:00
|
|
|
from datetime import datetime
|
2024-01-15 08:46:22 +08:00
|
|
|
import json
|
2024-12-12 17:47:39 +08:00
|
|
|
import xxhash
|
2024-01-15 08:46:22 +08:00
|
|
|
import copy
|
|
|
|
import re
|
2024-01-31 19:57:45 +08:00
|
|
|
from functools import partial
|
2024-09-29 09:49:45 +08:00
|
|
|
from io import BytesIO
|
2024-04-10 10:11:22 +08:00
|
|
|
from multiprocessing.context import TimeoutError
|
2024-04-22 14:11:09 +08:00
|
|
|
from timeit import default_timer as timer
|
2024-11-22 12:00:25 +08:00
|
|
|
import tracemalloc
|
2025-02-24 16:21:55 +08:00
|
|
|
import signal
|
2025-03-03 18:59:49 +08:00
|
|
|
import trio
|
2025-03-10 15:15:06 +08:00
|
|
|
import exceptiongroup
|
2025-03-13 14:37:59 +08:00
|
|
|
import faulthandler
|
2024-01-15 19:47:25 +08:00
|
|
|
|
2024-09-29 09:49:45 +08:00
|
|
|
import numpy as np
|
2024-12-12 16:38:03 +08:00
|
|
|
from peewee import DoesNotExist
|
2024-01-31 19:57:45 +08:00
|
|
|
|
2024-12-12 16:38:03 +08:00
|
|
|
from api.db import LLMType, ParserType, TaskStatus
|
2024-01-17 20:20:42 +08:00
|
|
|
from api.db.services.document_service import DocumentService
|
2024-01-31 19:57:45 +08:00
|
|
|
from api.db.services.llm_service import LLMBundle
|
2024-09-29 09:49:45 +08:00
|
|
|
from api.db.services.task_service import TaskService
|
|
|
|
from api.db.services.file2document_service import File2DocumentService
|
2024-11-15 17:30:56 +08:00
|
|
|
from api import settings
|
2024-11-30 18:48:06 +08:00
|
|
|
from api.versions import get_ragflow_version
|
2024-09-29 09:49:45 +08:00
|
|
|
from api.db.db_models import close_connection
|
2024-11-15 17:30:56 +08:00
|
|
|
from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one, audio, \
|
2025-01-22 19:43:14 +08:00
|
|
|
email, tag
|
2024-09-29 09:49:45 +08:00
|
|
|
from rag.nlp import search, rag_tokenizer
|
|
|
|
from rag.raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
|
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"
/>
2025-06-16 13:40:47 +08:00
|
|
|
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
|
2025-03-21 12:43:32 +08:00
|
|
|
from rag.utils import num_tokens_from_string, truncate
|
2025-04-19 16:18:51 +08:00
|
|
|
from rag.utils.redis_conn import REDIS_CONN, RedisDistributedLock
|
2024-09-29 09:49:45 +08:00
|
|
|
from rag.utils.storage_factory import STORAGE_IMPL
|
2025-03-03 18:59:49 +08:00
|
|
|
from graphrag.utils import chat_limiter
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
|
|
BATCH_SIZE = 64
|
|
|
|
|
2024-01-31 19:57:45 +08:00
|
|
|
FACTORY = {
|
2024-03-04 14:42:26 +08:00
|
|
|
"general": naive,
|
2024-02-29 14:03:07 +08:00
|
|
|
ParserType.NAIVE.value: naive,
|
2024-01-31 19:57:45 +08:00
|
|
|
ParserType.PAPER.value: paper,
|
2024-02-05 18:08:17 +08:00
|
|
|
ParserType.BOOK.value: book,
|
2024-01-31 19:57:45 +08:00
|
|
|
ParserType.PRESENTATION.value: presentation,
|
|
|
|
ParserType.MANUAL.value: manual,
|
|
|
|
ParserType.LAWS.value: laws,
|
2024-02-01 18:53:56 +08:00
|
|
|
ParserType.QA.value: qa,
|
2024-02-05 18:08:17 +08:00
|
|
|
ParserType.TABLE.value: table,
|
2024-02-08 17:01:01 +08:00
|
|
|
ParserType.RESUME.value: resume,
|
2024-02-23 18:28:12 +08:00
|
|
|
ParserType.PICTURE.value: picture,
|
2024-03-20 18:57:22 +08:00
|
|
|
ParserType.ONE.value: one,
|
2024-08-02 18:51:14 +08:00
|
|
|
ParserType.AUDIO.value: audio,
|
2024-08-06 16:42:14 +08:00
|
|
|
ParserType.EMAIL.value: email,
|
2025-01-22 19:43:14 +08:00
|
|
|
ParserType.KG.value: naive,
|
2025-01-09 17:07:21 +08:00
|
|
|
ParserType.TAG.value: tag
|
2024-01-31 19:57:45 +08:00
|
|
|
}
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
UNACKED_ITERATOR = None
|
2025-03-14 14:13:47 +08:00
|
|
|
|
|
|
|
CONSUMER_NO = "0" if len(sys.argv) < 2 else sys.argv[1]
|
|
|
|
CONSUMER_NAME = "task_executor_" + CONSUMER_NO
|
2024-12-23 17:25:55 +08:00
|
|
|
BOOT_AT = datetime.now().astimezone().isoformat(timespec="milliseconds")
|
2024-11-15 14:43:55 +08:00
|
|
|
PENDING_TASKS = 0
|
2024-11-15 18:51:09 +08:00
|
|
|
LAG_TASKS = 0
|
2024-11-15 22:55:41 +08:00
|
|
|
DONE_TASKS = 0
|
|
|
|
FAILED_TASKS = 0
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
CURRENT_TASKS = {}
|
|
|
|
|
|
|
|
MAX_CONCURRENT_TASKS = int(os.environ.get('MAX_CONCURRENT_TASKS', "5"))
|
|
|
|
MAX_CONCURRENT_CHUNK_BUILDERS = int(os.environ.get('MAX_CONCURRENT_CHUNK_BUILDERS', "1"))
|
2025-05-06 14:39:45 +08:00
|
|
|
MAX_CONCURRENT_MINIO = int(os.environ.get('MAX_CONCURRENT_MINIO', '10'))
|
2025-06-06 03:32:35 -03:00
|
|
|
task_limiter = trio.Semaphore(MAX_CONCURRENT_TASKS)
|
2025-03-03 18:59:49 +08:00
|
|
|
chunk_limiter = trio.CapacityLimiter(MAX_CONCURRENT_CHUNK_BUILDERS)
|
2025-05-06 14:39:45 +08:00
|
|
|
minio_limiter = trio.CapacityLimiter(MAX_CONCURRENT_MINIO)
|
2025-05-27 11:16:29 +08:00
|
|
|
kg_limiter = trio.CapacityLimiter(2)
|
2025-04-19 16:18:51 +08:00
|
|
|
WORKER_HEARTBEAT_TIMEOUT = int(os.environ.get('WORKER_HEARTBEAT_TIMEOUT', '120'))
|
|
|
|
stop_event = threading.Event()
|
|
|
|
|
|
|
|
|
|
|
|
def signal_handler(sig, frame):
|
|
|
|
logging.info("Received interrupt signal, shutting down...")
|
|
|
|
stop_event.set()
|
|
|
|
time.sleep(1)
|
|
|
|
sys.exit(0)
|
2025-02-24 16:21:55 +08:00
|
|
|
|
2025-03-17 11:58:40 +08:00
|
|
|
|
2025-02-24 16:21:55 +08:00
|
|
|
# SIGUSR1 handler: start tracemalloc and take snapshot
|
|
|
|
def start_tracemalloc_and_snapshot(signum, frame):
|
2025-03-03 18:59:49 +08:00
|
|
|
if not tracemalloc.is_tracing():
|
|
|
|
logging.info("start tracemalloc")
|
2025-02-24 16:21:55 +08:00
|
|
|
tracemalloc.start()
|
|
|
|
else:
|
2025-03-03 18:59:49 +08:00
|
|
|
logging.info("tracemalloc is already running")
|
2025-02-24 16:21:55 +08:00
|
|
|
|
|
|
|
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
|
snapshot_file = f"snapshot_{timestamp}.trace"
|
|
|
|
snapshot_file = os.path.abspath(os.path.join(get_project_base_directory(), "logs", f"{os.getpid()}_snapshot_{timestamp}.trace"))
|
|
|
|
|
|
|
|
snapshot = tracemalloc.take_snapshot()
|
|
|
|
snapshot.dump(snapshot_file)
|
2025-03-03 18:59:49 +08:00
|
|
|
current, peak = tracemalloc.get_traced_memory()
|
2025-03-12 09:43:18 +08:00
|
|
|
if sys.platform == "win32":
|
|
|
|
import psutil
|
|
|
|
process = psutil.Process()
|
|
|
|
max_rss = process.memory_info().rss / 1024
|
|
|
|
else:
|
|
|
|
import resource
|
|
|
|
max_rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
2025-03-03 18:59:49 +08:00
|
|
|
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")
|
2025-02-24 16:21:55 +08:00
|
|
|
|
|
|
|
# SIGUSR2 handler: stop tracemalloc
|
|
|
|
def stop_tracemalloc(signum, frame):
|
2025-03-03 18:59:49 +08:00
|
|
|
if tracemalloc.is_tracing():
|
|
|
|
logging.info("stop tracemalloc")
|
2025-02-24 16:21:55 +08:00
|
|
|
tracemalloc.stop()
|
|
|
|
else:
|
2025-03-03 18:59:49 +08:00
|
|
|
logging.info("tracemalloc not running")
|
2024-12-31 14:31:31 +08:00
|
|
|
|
2024-12-12 16:38:03 +08:00
|
|
|
class TaskCanceledException(Exception):
|
|
|
|
def __init__(self, msg):
|
|
|
|
self.msg = msg
|
2024-11-15 17:30:56 +08:00
|
|
|
|
2024-12-31 14:31:31 +08:00
|
|
|
|
2024-09-29 09:49:45 +08:00
|
|
|
def set_progress(task_id, from_page=0, to_page=-1, prog=None, msg="Processing..."):
|
2025-03-13 14:37:59 +08:00
|
|
|
try:
|
|
|
|
if prog is not None and prog < 0:
|
|
|
|
msg = "[ERROR]" + msg
|
|
|
|
cancel = TaskService.do_cancel(task_id)
|
|
|
|
|
|
|
|
if cancel:
|
|
|
|
msg += " [Canceled]"
|
|
|
|
prog = -1
|
|
|
|
|
|
|
|
if to_page > 0:
|
|
|
|
if msg:
|
|
|
|
if from_page < to_page:
|
|
|
|
msg = f"Page({from_page + 1}~{to_page + 1}): " + msg
|
2024-03-05 12:08:41 +08:00
|
|
|
if msg:
|
2025-03-13 14:37:59 +08:00
|
|
|
msg = datetime.now().strftime("%H:%M:%S") + " " + msg
|
|
|
|
d = {"progress_msg": msg}
|
|
|
|
if prog is not None:
|
|
|
|
d["progress"] = prog
|
|
|
|
|
|
|
|
TaskService.update_progress(task_id, d)
|
|
|
|
|
|
|
|
close_connection()
|
|
|
|
if cancel:
|
|
|
|
raise TaskCanceledException(msg)
|
|
|
|
logging.info(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}")
|
|
|
|
except DoesNotExist:
|
|
|
|
logging.warning(f"set_progress({task_id}) got exception DoesNotExist")
|
|
|
|
except Exception:
|
|
|
|
logging.exception(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}, got exception")
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def collect():
|
|
|
|
global CONSUMER_NAME, DONE_TASKS, FAILED_TASKS
|
|
|
|
global UNACKED_ITERATOR
|
2025-06-12 19:09:50 +08:00
|
|
|
|
2025-06-13 16:38:53 +08:00
|
|
|
svr_queue_names = get_svr_queue_names()
|
2024-05-07 11:43:33 +08:00
|
|
|
try:
|
2025-03-03 18:59:49 +08:00
|
|
|
if not UNACKED_ITERATOR:
|
2025-06-13 16:38:53 +08:00
|
|
|
UNACKED_ITERATOR = REDIS_CONN.get_unacked_iterator(svr_queue_names, SVR_CONSUMER_GROUP_NAME, CONSUMER_NAME)
|
|
|
|
try:
|
|
|
|
redis_msg = next(UNACKED_ITERATOR)
|
|
|
|
except StopIteration:
|
2025-03-14 23:43:46 +08:00
|
|
|
for svr_queue_name in svr_queue_names:
|
2025-06-13 16:38:53 +08:00
|
|
|
redis_msg = REDIS_CONN.queue_consumer(svr_queue_name, SVR_CONSUMER_GROUP_NAME, CONSUMER_NAME)
|
|
|
|
if redis_msg:
|
|
|
|
break
|
|
|
|
except Exception:
|
|
|
|
logging.exception("collect got exception")
|
2025-03-03 18:59:49 +08:00
|
|
|
return None, None
|
2024-05-07 11:43:33 +08:00
|
|
|
|
2025-03-14 23:43:46 +08:00
|
|
|
if not redis_msg:
|
|
|
|
return None, None
|
2025-03-03 18:59:49 +08:00
|
|
|
msg = redis_msg.get_message()
|
2024-08-28 14:06:27 +08:00
|
|
|
if not msg:
|
2025-03-03 18:59:49 +08:00
|
|
|
logging.error(f"collect got empty message of {redis_msg.get_msg_id()}")
|
|
|
|
redis_msg.ack()
|
|
|
|
return None, None
|
2024-05-07 11:43:33 +08:00
|
|
|
|
2024-12-12 16:38:03 +08:00
|
|
|
canceled = False
|
2025-03-03 18:59:49 +08:00
|
|
|
task = TaskService.get_task(msg["id"])
|
|
|
|
if task:
|
|
|
|
_, doc = DocumentService.get_by_id(task["doc_id"])
|
|
|
|
canceled = doc.run == TaskStatus.CANCEL.value or doc.progress < 0
|
2024-12-12 16:38:03 +08:00
|
|
|
if not task or canceled:
|
|
|
|
state = "is unknown" if not task else "has been cancelled"
|
2025-03-03 18:59:49 +08:00
|
|
|
FAILED_TASKS += 1
|
|
|
|
logging.warning(f"collect task {msg['id']} {state}")
|
|
|
|
redis_msg.ack()
|
2025-03-05 14:48:03 +08:00
|
|
|
return None, None
|
2025-01-22 19:43:14 +08:00
|
|
|
task["task_type"] = msg.get("task_type", "")
|
2025-03-03 18:59:49 +08:00
|
|
|
return redis_msg, task
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2024-04-08 19:20:57 +08:00
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def get_storage_binary(bucket, name):
|
|
|
|
return await trio.to_thread.run_sync(lambda: STORAGE_IMPL.get(bucket, name))
|
2024-04-08 19:20:57 +08:00
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def build_chunks(task, progress_callback):
|
2024-12-01 22:28:00 +08:00
|
|
|
if task["size"] > DOC_MAXIMUM_SIZE:
|
|
|
|
set_progress(task["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
|
|
|
|
(int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
|
2024-01-15 08:46:22 +08:00
|
|
|
return []
|
2024-01-15 19:47:25 +08:00
|
|
|
|
2024-12-01 22:28:00 +08:00
|
|
|
chunker = FACTORY[task["parser_id"].lower()]
|
2024-01-15 08:46:22 +08:00
|
|
|
try:
|
2024-04-08 19:20:57 +08:00
|
|
|
st = timer()
|
2024-12-01 22:28:00 +08:00
|
|
|
bucket, name = File2DocumentService.get_storage_address(doc_id=task["doc_id"])
|
2025-03-03 18:59:49 +08:00
|
|
|
binary = await get_storage_binary(bucket, name)
|
2024-12-01 22:28:00 +08:00
|
|
|
logging.info("From minio({}) {}/{}".format(timer() - st, task["location"], task["name"]))
|
2024-09-29 09:49:45 +08:00
|
|
|
except TimeoutError:
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_callback(-1, "Internal server error: Fetch file from minio timeout. Could you try it again.")
|
2025-01-09 17:07:21 +08:00
|
|
|
logging.exception(
|
|
|
|
"Minio {}/{} got timeout: Fetch file from minio timeout.".format(task["location"], task["name"]))
|
2024-11-15 18:51:09 +08:00
|
|
|
raise
|
2024-01-15 08:46:22 +08:00
|
|
|
except Exception as e:
|
|
|
|
if re.search("(No such file|not found)", str(e)):
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_callback(-1, "Can not find file <%s> from minio. Could you try it again?" % task["name"])
|
2024-01-15 08:46:22 +08:00
|
|
|
else:
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_callback(-1, "Get file from minio: %s" % str(e).replace("'", ""))
|
|
|
|
logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
|
2024-11-15 18:51:09 +08:00
|
|
|
raise
|
2024-01-15 19:47:25 +08:00
|
|
|
|
2024-08-14 11:09:07 +08:00
|
|
|
try:
|
2025-03-03 18:59:49 +08:00
|
|
|
async with chunk_limiter:
|
|
|
|
cks = await trio.to_thread.run_sync(lambda: chunker.chunk(task["name"], binary=binary, from_page=task["from_page"],
|
2025-03-17 16:49:54 +08:00
|
|
|
to_page=task["to_page"], lang=task["language"], callback=progress_callback,
|
2025-03-03 18:59:49 +08:00
|
|
|
kb_id=task["kb_id"], parser_config=task["parser_config"], tenant_id=task["tenant_id"]))
|
2024-12-01 22:28:00 +08:00
|
|
|
logging.info("Chunking({}) {}/{} done".format(timer() - st, task["location"], task["name"]))
|
2024-12-12 16:38:03 +08:00
|
|
|
except TaskCanceledException:
|
|
|
|
raise
|
2024-08-14 11:09:07 +08:00
|
|
|
except Exception as e:
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_callback(-1, "Internal server error while chunking: %s" % str(e).replace("'", ""))
|
|
|
|
logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
|
2024-11-15 18:51:09 +08:00
|
|
|
raise
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2024-01-31 19:57:45 +08:00
|
|
|
docs = []
|
2024-01-15 08:46:22 +08:00
|
|
|
doc = {
|
2024-12-01 22:28:00 +08:00
|
|
|
"doc_id": task["doc_id"],
|
|
|
|
"kb_id": str(task["kb_id"])
|
2024-01-15 08:46:22 +08:00
|
|
|
}
|
2024-12-08 14:21:12 +08:00
|
|
|
if task["pagerank"]:
|
2025-01-09 17:07:21 +08:00
|
|
|
doc[PAGERANK_FLD] = int(task["pagerank"])
|
2025-05-06 14:39:45 +08:00
|
|
|
st = timer()
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2025-05-06 14:39:45 +08:00
|
|
|
async def upload_to_minio(document, chunk):
|
2024-08-30 18:41:31 +08:00
|
|
|
try:
|
2025-05-27 17:49:37 +08:00
|
|
|
d = copy.deepcopy(document)
|
|
|
|
d.update(chunk)
|
|
|
|
d["id"] = xxhash.xxh64((chunk["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
|
|
|
|
d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
|
|
|
|
d["create_timestamp_flt"] = datetime.now().timestamp()
|
|
|
|
if not d.get("image"):
|
|
|
|
_ = d.pop("image", None)
|
|
|
|
d["img_id"] = ""
|
|
|
|
docs.append(d)
|
|
|
|
return
|
|
|
|
|
|
|
|
output_buffer = BytesIO()
|
|
|
|
if isinstance(d["image"], bytes):
|
|
|
|
output_buffer = BytesIO(d["image"])
|
|
|
|
else:
|
|
|
|
d["image"].save(output_buffer, format='JPEG')
|
2025-05-06 14:39:45 +08:00
|
|
|
async with minio_limiter:
|
|
|
|
await trio.to_thread.run_sync(lambda: STORAGE_IMPL.put(task["kb_id"], d["id"], output_buffer.getvalue()))
|
2025-05-27 17:49:37 +08:00
|
|
|
d["img_id"] = "{}-{}".format(task["kb_id"], d["id"])
|
|
|
|
del d["image"]
|
|
|
|
docs.append(d)
|
2024-11-12 17:35:13 +08:00
|
|
|
except Exception:
|
2025-01-09 17:07:21 +08:00
|
|
|
logging.exception(
|
|
|
|
"Saving image of chunk {}/{}/{} got exception".format(task["location"], task["name"], d["id"]))
|
2024-11-15 18:51:09 +08:00
|
|
|
raise
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2025-05-06 14:39:45 +08:00
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
for ck in cks:
|
|
|
|
nursery.start_soon(upload_to_minio, doc, ck)
|
|
|
|
|
|
|
|
el = timer() - st
|
|
|
|
logging.info("MINIO PUT({}) cost {:.3f} s".format(task["name"], el))
|
2024-01-15 08:46:22 +08:00
|
|
|
|
2024-12-01 22:28:00 +08:00
|
|
|
if task["parser_config"].get("auto_keywords", 0):
|
2024-11-14 16:28:10 +08:00
|
|
|
st = timer()
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_callback(msg="Start to generate keywords for every chunk ...")
|
|
|
|
chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
|
2024-12-17 09:48:03 +08:00
|
|
|
|
2025-02-26 15:21:14 +08:00
|
|
|
async def doc_keyword_extraction(chat_mdl, d, topn):
|
|
|
|
cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "keywords", {"topn": topn})
|
|
|
|
if not cached:
|
2025-03-03 18:59:49 +08:00
|
|
|
async with chat_limiter:
|
|
|
|
cached = await trio.to_thread.run_sync(lambda: keyword_extraction(chat_mdl, d["content_with_weight"], topn))
|
2025-02-26 15:21:14 +08:00
|
|
|
set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "keywords", {"topn": topn})
|
|
|
|
if cached:
|
|
|
|
d["important_kwd"] = cached.split(",")
|
|
|
|
d["important_tks"] = rag_tokenizer.tokenize(" ".join(d["important_kwd"]))
|
|
|
|
return
|
2025-03-03 18:59:49 +08:00
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
for d in docs:
|
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.
2025-04-18 18:00:20 +08:00
|
|
|
nursery.start_soon(doc_keyword_extraction, chat_mdl, d, task["parser_config"]["auto_keywords"])
|
2025-02-26 15:21:14 +08:00
|
|
|
progress_callback(msg="Keywords generation {} chunks completed in {:.2f}s".format(len(docs), timer() - st))
|
2024-10-23 17:00:56 +08:00
|
|
|
|
2024-12-01 22:28:00 +08:00
|
|
|
if task["parser_config"].get("auto_questions", 0):
|
2024-11-14 16:28:10 +08:00
|
|
|
st = timer()
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_callback(msg="Start to generate questions for every chunk ...")
|
|
|
|
chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
|
2024-12-17 09:48:03 +08:00
|
|
|
|
2025-02-26 15:21:14 +08:00
|
|
|
async def doc_question_proposal(chat_mdl, d, topn):
|
|
|
|
cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "question", {"topn": topn})
|
|
|
|
if not cached:
|
2025-03-03 18:59:49 +08:00
|
|
|
async with chat_limiter:
|
|
|
|
cached = await trio.to_thread.run_sync(lambda: question_proposal(chat_mdl, d["content_with_weight"], topn))
|
2025-02-26 15:21:14 +08:00
|
|
|
set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "question", {"topn": topn})
|
|
|
|
if cached:
|
|
|
|
d["question_kwd"] = cached.split("\n")
|
|
|
|
d["question_tks"] = rag_tokenizer.tokenize("\n".join(d["question_kwd"]))
|
2025-03-03 18:59:49 +08:00
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
for d in docs:
|
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.
2025-04-18 18:00:20 +08:00
|
|
|
nursery.start_soon(doc_question_proposal, chat_mdl, d, task["parser_config"]["auto_questions"])
|
2025-02-26 15:21:14 +08:00
|
|
|
progress_callback(msg="Question generation {} chunks completed in {:.2f}s".format(len(docs), timer() - st))
|
2024-10-23 17:00:56 +08:00
|
|
|
|
2025-01-09 17:07:21 +08:00
|
|
|
if task["kb_parser_config"].get("tag_kb_ids", []):
|
|
|
|
progress_callback(msg="Start to tag for every chunk ...")
|
|
|
|
kb_ids = task["kb_parser_config"]["tag_kb_ids"]
|
|
|
|
tenant_id = task["tenant_id"]
|
|
|
|
topn_tags = task["kb_parser_config"].get("topn_tags", 3)
|
|
|
|
S = 1000
|
|
|
|
st = timer()
|
|
|
|
examples = []
|
|
|
|
all_tags = get_tags_from_cache(kb_ids)
|
|
|
|
if not all_tags:
|
|
|
|
all_tags = settings.retrievaler.all_tags_in_portion(tenant_id, kb_ids, S)
|
|
|
|
set_tags_to_cache(kb_ids, all_tags)
|
|
|
|
else:
|
|
|
|
all_tags = json.loads(all_tags)
|
|
|
|
|
|
|
|
chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
|
2025-02-26 15:21:14 +08:00
|
|
|
|
|
|
|
docs_to_tag = []
|
2025-01-09 17:07:21 +08:00
|
|
|
for d in docs:
|
2025-05-22 09:28:08 +08:00
|
|
|
task_canceled = TaskService.do_cancel(task["id"])
|
|
|
|
if task_canceled:
|
|
|
|
progress_callback(-1, msg="Task has been canceled.")
|
|
|
|
return
|
2025-05-09 10:17:24 +08:00
|
|
|
if settings.retrievaler.tag_content(tenant_id, kb_ids, d, all_tags, topn_tags=topn_tags, S=S) and len(d[TAG_FLD]) > 0:
|
2025-01-09 17:07:21 +08:00
|
|
|
examples.append({"content": d["content_with_weight"], TAG_FLD: d[TAG_FLD]})
|
2025-02-26 15:21:14 +08:00
|
|
|
else:
|
|
|
|
docs_to_tag.append(d)
|
|
|
|
|
|
|
|
async def doc_content_tagging(chat_mdl, d, topn_tags):
|
2025-01-09 17:07:21 +08:00
|
|
|
cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], all_tags, {"topn": topn_tags})
|
|
|
|
if not cached:
|
2025-02-26 15:21:14 +08:00
|
|
|
picked_examples = random.choices(examples, k=2) if len(examples)>2 else examples
|
2025-03-19 17:30:47 +08:00
|
|
|
if not picked_examples:
|
|
|
|
picked_examples.append({"content": "This is an example", TAG_FLD: {'example': 1}})
|
2025-03-03 18:59:49 +08:00
|
|
|
async with chat_limiter:
|
|
|
|
cached = await trio.to_thread.run_sync(lambda: content_tagging(chat_mdl, d["content_with_weight"], all_tags, picked_examples, topn=topn_tags))
|
2025-01-09 17:07:21 +08:00
|
|
|
if cached:
|
2025-01-23 17:26:20 +08:00
|
|
|
cached = json.dumps(cached)
|
|
|
|
if cached:
|
|
|
|
set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, all_tags, {"topn": topn_tags})
|
|
|
|
d[TAG_FLD] = json.loads(cached)
|
2025-03-03 18:59:49 +08:00
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
for d in docs_to_tag:
|
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.
2025-04-18 18:00:20 +08:00
|
|
|
nursery.start_soon(doc_content_tagging, chat_mdl, d, topn_tags)
|
2025-02-26 15:21:14 +08:00
|
|
|
progress_callback(msg="Tagging {} chunks completed in {:.2f}s".format(len(docs), timer() - st))
|
2025-01-09 17:07:21 +08:00
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
return docs
|
|
|
|
|
|
|
|
|
2024-11-12 14:59:41 +08:00
|
|
|
def init_kb(row, vector_size: int):
|
2024-01-15 08:46:22 +08:00
|
|
|
idxnm = search.index_name(row["tenant_id"])
|
2025-01-09 17:07:21 +08:00
|
|
|
return settings.docStoreConn.createIdx(idxnm, row.get("kb_id", ""), vector_size)
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def embedding(docs, mdl, parser_config=None, callback=None):
|
2024-09-29 09:49:45 +08:00
|
|
|
if parser_config is None:
|
|
|
|
parser_config = {}
|
2024-12-05 14:51:19 +08:00
|
|
|
tts, cnts = [], []
|
|
|
|
for d in docs:
|
2024-12-11 19:23:59 +08:00
|
|
|
tts.append(d.get("docnm_kwd", "Title"))
|
2024-12-05 14:51:19 +08:00
|
|
|
c = "\n".join(d.get("question_kwd", []))
|
|
|
|
if not c:
|
|
|
|
c = d["content_with_weight"]
|
|
|
|
c = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", c)
|
2024-12-31 14:31:31 +08:00
|
|
|
if not c:
|
|
|
|
c = "None"
|
2024-12-05 14:51:19 +08:00
|
|
|
cnts.append(c)
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
tk_count = 0
|
2024-02-01 18:53:56 +08:00
|
|
|
if len(tts) == len(cnts):
|
2025-03-03 18:59:49 +08:00
|
|
|
vts, c = await trio.to_thread.run_sync(lambda: mdl.encode(tts[0: 1]))
|
2025-01-15 15:20:29 +08:00
|
|
|
tts = np.concatenate([vts for _ in range(len(tts))], axis=0)
|
|
|
|
tk_count += c
|
2024-02-01 18:53:56 +08:00
|
|
|
|
2024-03-05 16:33:47 +08:00
|
|
|
cnts_ = np.array([])
|
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"
/>
2025-06-16 13:40:47 +08:00
|
|
|
for i in range(0, len(cnts), EMBEDDING_BATCH_SIZE):
|
|
|
|
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]]))
|
2024-03-27 11:33:46 +08:00
|
|
|
if len(cnts_) == 0:
|
|
|
|
cnts_ = vts
|
|
|
|
else:
|
|
|
|
cnts_ = np.concatenate((cnts_, vts), axis=0)
|
2024-03-05 12:08:41 +08:00
|
|
|
tk_count += c
|
2024-03-27 11:33:46 +08:00
|
|
|
callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
|
2024-03-05 12:08:41 +08:00
|
|
|
cnts = cnts_
|
|
|
|
|
2024-02-08 17:01:01 +08:00
|
|
|
title_w = float(parser_config.get("filename_embd_weight", 0.1))
|
2024-02-23 18:28:12 +08:00
|
|
|
vects = (title_w * tts + (1 - title_w) *
|
|
|
|
cnts) if len(tts) == len(cnts) else cnts
|
2024-02-01 18:53:56 +08:00
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
assert len(vects) == len(docs)
|
2024-11-12 14:59:41 +08:00
|
|
|
vector_size = 0
|
2024-01-15 08:46:22 +08:00
|
|
|
for i, d in enumerate(docs):
|
2024-01-17 09:39:50 +08:00
|
|
|
v = vects[i].tolist()
|
2024-11-12 14:59:41 +08:00
|
|
|
vector_size = len(v)
|
2024-01-31 19:57:45 +08:00
|
|
|
d["q_%d_vec" % len(v)] = v
|
2024-11-12 14:59:41 +08:00
|
|
|
return tk_count, vector_size
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def run_raptor(row, chat_mdl, embd_mdl, vector_size, callback=None):
|
2024-05-23 14:31:16 +08:00
|
|
|
chunks = []
|
2025-01-22 19:43:14 +08:00
|
|
|
vctr_nm = "q_%d_vec"%vector_size
|
2024-11-15 17:30:56 +08:00
|
|
|
for d in settings.retrievaler.chunk_list(row["doc_id"], row["tenant_id"], [str(row["kb_id"])],
|
|
|
|
fields=["content_with_weight", vctr_nm]):
|
2024-05-23 14:31:16 +08:00
|
|
|
chunks.append((d["content_with_weight"], np.array(d[vctr_nm])))
|
|
|
|
|
|
|
|
raptor = Raptor(
|
|
|
|
row["parser_config"]["raptor"].get("max_cluster", 64),
|
|
|
|
chat_mdl,
|
|
|
|
embd_mdl,
|
|
|
|
row["parser_config"]["raptor"]["prompt"],
|
|
|
|
row["parser_config"]["raptor"]["max_token"],
|
|
|
|
row["parser_config"]["raptor"]["threshold"]
|
|
|
|
)
|
|
|
|
original_length = len(chunks)
|
2025-03-03 18:59:49 +08:00
|
|
|
chunks = await raptor(chunks, row["parser_config"]["raptor"]["random_seed"], callback)
|
2024-05-23 14:31:16 +08:00
|
|
|
doc = {
|
|
|
|
"doc_id": row["doc_id"],
|
|
|
|
"kb_id": [str(row["kb_id"])],
|
|
|
|
"docnm_kwd": row["name"],
|
|
|
|
"title_tks": rag_tokenizer.tokenize(row["name"])
|
|
|
|
}
|
2024-12-08 14:21:12 +08:00
|
|
|
if row["pagerank"]:
|
2025-01-09 17:07:21 +08:00
|
|
|
doc[PAGERANK_FLD] = int(row["pagerank"])
|
2024-05-23 14:31:16 +08:00
|
|
|
res = []
|
|
|
|
tk_count = 0
|
|
|
|
for content, vctr in chunks[original_length:]:
|
|
|
|
d = copy.deepcopy(doc)
|
2024-12-12 17:47:39 +08:00
|
|
|
d["id"] = xxhash.xxh64((content + str(d["doc_id"])).encode("utf-8")).hexdigest()
|
2024-11-15 14:43:55 +08:00
|
|
|
d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
|
|
|
|
d["create_timestamp_flt"] = datetime.now().timestamp()
|
2024-05-23 14:31:16 +08:00
|
|
|
d[vctr_nm] = vctr.tolist()
|
|
|
|
d["content_with_weight"] = content
|
|
|
|
d["content_ltks"] = rag_tokenizer.tokenize(content)
|
|
|
|
d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
|
|
|
|
res.append(d)
|
|
|
|
tk_count += num_tokens_from_string(content)
|
2025-01-22 19:43:14 +08:00
|
|
|
return res, tk_count
|
|
|
|
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def do_handle_task(task):
|
2024-12-01 17:03:00 +08:00
|
|
|
task_id = task["id"]
|
|
|
|
task_from_page = task["from_page"]
|
|
|
|
task_to_page = task["to_page"]
|
|
|
|
task_tenant_id = task["tenant_id"]
|
|
|
|
task_embedding_id = task["embd_id"]
|
|
|
|
task_language = task["language"]
|
|
|
|
task_llm_id = task["llm_id"]
|
|
|
|
task_dataset_id = task["kb_id"]
|
|
|
|
task_doc_id = task["doc_id"]
|
|
|
|
task_document_name = task["name"]
|
|
|
|
task_parser_config = task["parser_config"]
|
2025-03-03 18:59:49 +08:00
|
|
|
task_start_ts = timer()
|
2024-12-01 17:03:00 +08:00
|
|
|
|
|
|
|
# prepare the progress callback function
|
|
|
|
progress_callback = partial(set_progress, task_id, task_from_page, task_to_page)
|
2024-12-12 16:38:03 +08:00
|
|
|
|
2025-01-10 16:39:13 +08:00
|
|
|
# FIXME: workaround, Infinity doesn't support table parsing method, this check is to notify user
|
|
|
|
lower_case_doc_engine = settings.DOC_ENGINE.lower()
|
|
|
|
if lower_case_doc_engine == 'infinity' and task['parser_id'].lower() == 'table':
|
|
|
|
error_message = "Table parsing method is not supported by Infinity, please use other parsing methods or use Elasticsearch as the document engine."
|
|
|
|
progress_callback(-1, msg=error_message)
|
|
|
|
raise Exception(error_message)
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
task_canceled = TaskService.do_cancel(task_id)
|
2024-12-12 16:38:03 +08:00
|
|
|
if task_canceled:
|
|
|
|
progress_callback(-1, msg="Task has been canceled.")
|
|
|
|
return
|
|
|
|
|
2024-11-15 18:51:09 +08:00
|
|
|
try:
|
2024-12-01 17:03:00 +08:00
|
|
|
# bind embedding model
|
|
|
|
embedding_model = LLMBundle(task_tenant_id, LLMType.EMBEDDING, llm_name=task_embedding_id, lang=task_language)
|
2025-02-28 17:52:38 +08:00
|
|
|
vts, _ = embedding_model.encode(["ok"])
|
|
|
|
vector_size = len(vts[0])
|
2024-11-15 18:51:09 +08:00
|
|
|
except Exception as e:
|
2024-12-01 22:28:00 +08:00
|
|
|
error_message = f'Fail to bind embedding model: {str(e)}'
|
|
|
|
progress_callback(-1, msg=error_message)
|
|
|
|
logging.exception(error_message)
|
2024-11-15 18:51:09 +08:00
|
|
|
raise
|
2024-12-01 17:03:00 +08:00
|
|
|
|
2025-01-22 19:43:14 +08:00
|
|
|
init_kb(task, vector_size)
|
|
|
|
|
2024-12-01 17:03:00 +08:00
|
|
|
# Either using RAPTOR or Standard chunking methods
|
|
|
|
if task.get("task_type", "") == "raptor":
|
2025-03-03 18:59:49 +08:00
|
|
|
# bind LLM for raptor
|
|
|
|
chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
|
|
|
|
# run RAPTOR
|
2025-05-27 17:41:35 +08:00
|
|
|
async with kg_limiter:
|
|
|
|
chunks, token_count = await run_raptor(task, chat_model, embedding_model, vector_size, progress_callback)
|
2025-01-22 19:43:14 +08:00
|
|
|
# Either using graphrag or Standard chunking methods
|
|
|
|
elif task.get("task_type", "") == "graphrag":
|
2025-05-13 09:21:03 +08:00
|
|
|
if not task_parser_config.get("graphrag", {}).get("use_graphrag", False):
|
2025-03-05 14:48:03 +08:00
|
|
|
return
|
2025-05-13 09:21:03 +08:00
|
|
|
graphrag_conf = task["kb_parser_config"].get("graphrag", {})
|
2025-01-22 19:43:14 +08:00
|
|
|
start_ts = timer()
|
2025-03-03 18:59:49 +08:00
|
|
|
chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
|
2025-03-10 15:15:06 +08:00
|
|
|
with_resolution = graphrag_conf.get("resolution", False)
|
|
|
|
with_community = graphrag_conf.get("community", False)
|
2025-05-27 11:16:29 +08:00
|
|
|
async with kg_limiter:
|
|
|
|
await run_graphrag(task, task_language, with_resolution, with_community, chat_model, embedding_model, progress_callback)
|
2025-03-10 15:15:06 +08:00
|
|
|
progress_callback(prog=1.0, msg="Knowledge Graph done ({:.2f}s)".format(timer() - start_ts))
|
2025-01-22 19:43:14 +08:00
|
|
|
return
|
2024-11-15 18:51:09 +08:00
|
|
|
else:
|
2024-12-01 17:03:00 +08:00
|
|
|
# Standard chunking methods
|
|
|
|
start_ts = timer()
|
2025-03-03 18:59:49 +08:00
|
|
|
chunks = await build_chunks(task, progress_callback)
|
2024-12-01 17:03:00 +08:00
|
|
|
logging.info("Build document {}: {:.2f}s".format(task_document_name, timer() - start_ts))
|
|
|
|
if chunks is None:
|
2024-11-15 18:51:09 +08:00
|
|
|
return
|
2024-12-01 17:03:00 +08:00
|
|
|
if not chunks:
|
|
|
|
progress_callback(1., msg=f"No chunk built from {task_document_name}")
|
2024-11-15 18:51:09 +08:00
|
|
|
return
|
|
|
|
# TODO: exception handler
|
2024-12-01 17:03:00 +08:00
|
|
|
## set_progress(task["did"], -1, "ERROR: ")
|
|
|
|
progress_callback(msg="Generate {} chunks".format(len(chunks)))
|
|
|
|
start_ts = timer()
|
2024-11-15 18:51:09 +08:00
|
|
|
try:
|
2025-03-03 18:59:49 +08:00
|
|
|
token_count, vector_size = await embedding(chunks, embedding_model, task_parser_config, progress_callback)
|
2024-11-15 18:51:09 +08:00
|
|
|
except Exception as e:
|
2024-12-01 22:28:00 +08:00
|
|
|
error_message = "Generate embedding error:{}".format(str(e))
|
|
|
|
progress_callback(-1, error_message)
|
|
|
|
logging.exception(error_message)
|
|
|
|
token_count = 0
|
2024-11-15 18:51:09 +08:00
|
|
|
raise
|
2024-12-01 22:28:00 +08:00
|
|
|
progress_message = "Embedding chunks ({:.2f}s)".format(timer() - start_ts)
|
|
|
|
logging.info(progress_message)
|
|
|
|
progress_callback(msg=progress_message)
|
2024-12-12 16:38:03 +08:00
|
|
|
|
2024-12-01 17:03:00 +08:00
|
|
|
chunk_count = len(set([chunk["id"] for chunk in chunks]))
|
|
|
|
start_ts = timer()
|
2024-12-01 22:28:00 +08:00
|
|
|
doc_store_result = ""
|
2025-05-21 10:22:30 +08:00
|
|
|
|
|
|
|
async def delete_image(kb_id, chunk_id):
|
|
|
|
try:
|
|
|
|
async with minio_limiter:
|
|
|
|
STORAGE_IMPL.delete(kb_id, chunk_id)
|
|
|
|
except Exception:
|
|
|
|
logging.exception(
|
|
|
|
"Deleting image of chunk {}/{}/{} got exception".format(task["location"], task["name"], chunk_id))
|
|
|
|
raise
|
|
|
|
|
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"
/>
2025-06-16 13:40:47 +08:00
|
|
|
for b in range(0, len(chunks), DOC_BULK_SIZE):
|
|
|
|
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))
|
2025-05-22 09:28:08 +08:00
|
|
|
task_canceled = TaskService.do_cancel(task_id)
|
|
|
|
if task_canceled:
|
|
|
|
progress_callback(-1, msg="Task has been canceled.")
|
|
|
|
return
|
2024-11-15 18:51:09 +08:00
|
|
|
if b % 128 == 0:
|
2024-12-01 17:03:00 +08:00
|
|
|
progress_callback(prog=0.8 + 0.1 * (b + 1) / len(chunks), msg="")
|
2024-12-12 16:38:03 +08:00
|
|
|
if doc_store_result:
|
|
|
|
error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
|
|
|
|
progress_callback(-1, msg=error_message)
|
|
|
|
raise Exception(error_message)
|
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"
/>
2025-06-16 13:40:47 +08:00
|
|
|
chunk_ids = [chunk["id"] for chunk in chunks[:b + DOC_BULK_SIZE]]
|
2024-12-12 16:38:03 +08:00
|
|
|
chunk_ids_str = " ".join(chunk_ids)
|
|
|
|
try:
|
|
|
|
TaskService.update_chunk_ids(task["id"], chunk_ids_str)
|
|
|
|
except DoesNotExist:
|
|
|
|
logging.warning(f"do_handle_task update_chunk_ids failed since task {task['id']} is unknown.")
|
2025-03-03 18:59:49 +08:00
|
|
|
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))
|
2025-05-21 10:22:30 +08:00
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
for chunk_id in chunk_ids:
|
|
|
|
nursery.start_soon(delete_image, task_dataset_id, chunk_id)
|
2024-12-12 16:38:03 +08:00
|
|
|
return
|
2025-05-21 10:22:30 +08:00
|
|
|
|
2025-01-09 17:07:21 +08:00
|
|
|
logging.info("Indexing doc({}), page({}-{}), chunks({}), elapsed: {:.2f}".format(task_document_name, task_from_page,
|
|
|
|
task_to_page, len(chunks),
|
|
|
|
timer() - start_ts))
|
2024-11-15 18:51:09 +08:00
|
|
|
|
2024-12-01 22:28:00 +08:00
|
|
|
DocumentService.increment_chunk_num(task_doc_id, task_dataset_id, token_count, chunk_count, 0)
|
|
|
|
|
|
|
|
time_cost = timer() - start_ts
|
2025-03-03 18:59:49 +08:00
|
|
|
task_time_cost = timer() - task_start_ts
|
|
|
|
progress_callback(prog=1.0, msg="Indexing done ({:.2f}s). Task done ({:.2f}s)".format(time_cost, task_time_cost))
|
2025-01-09 17:07:21 +08:00
|
|
|
logging.info(
|
|
|
|
"Chunk doc({}), page({}-{}), chunks({}), token({}), elapsed:{:.2f}".format(task_document_name, task_from_page,
|
|
|
|
task_to_page, len(chunks),
|
2025-03-03 18:59:49 +08:00
|
|
|
token_count, task_time_cost))
|
2024-11-15 18:51:09 +08:00
|
|
|
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def handle_task():
|
|
|
|
global DONE_TASKS, FAILED_TASKS
|
|
|
|
redis_msg, task = await collect()
|
|
|
|
if not task:
|
2025-03-19 17:46:58 +08:00
|
|
|
await trio.sleep(5)
|
2025-03-03 18:59:49 +08:00
|
|
|
return
|
|
|
|
try:
|
|
|
|
logging.info(f"handle_task begin for task {json.dumps(task)}")
|
|
|
|
CURRENT_TASKS[task["id"]] = copy.deepcopy(task)
|
|
|
|
await do_handle_task(task)
|
|
|
|
DONE_TASKS += 1
|
|
|
|
CURRENT_TASKS.pop(task["id"], None)
|
|
|
|
logging.info(f"handle_task done for task {json.dumps(task)}")
|
|
|
|
except Exception as e:
|
|
|
|
FAILED_TASKS += 1
|
|
|
|
CURRENT_TASKS.pop(task["id"], None)
|
2024-11-15 18:51:09 +08:00
|
|
|
try:
|
2025-03-10 15:15:06 +08:00
|
|
|
err_msg = str(e)
|
|
|
|
while isinstance(e, exceptiongroup.ExceptionGroup):
|
|
|
|
e = e.exceptions[0]
|
|
|
|
err_msg += ' -- ' + str(e)
|
|
|
|
set_progress(task["id"], prog=-1, msg=f"[Exception]: {err_msg}")
|
2025-03-03 18:59:49 +08:00
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
logging.exception(f"handle_task got exception for task {json.dumps(task)}")
|
|
|
|
redis_msg.ack()
|
|
|
|
|
|
|
|
|
|
|
|
async def report_status():
|
|
|
|
global CONSUMER_NAME, BOOT_AT, PENDING_TASKS, LAG_TASKS, DONE_TASKS, FAILED_TASKS
|
2024-11-15 14:43:55 +08:00
|
|
|
REDIS_CONN.sadd("TASKEXE", CONSUMER_NAME)
|
2025-04-19 16:18:51 +08:00
|
|
|
redis_lock = RedisDistributedLock("clean_task_executor", lock_value=CONSUMER_NAME, timeout=60)
|
2024-08-21 17:48:00 +08:00
|
|
|
while True:
|
|
|
|
try:
|
2024-11-15 14:43:55 +08:00
|
|
|
now = datetime.now()
|
2025-03-14 23:43:46 +08:00
|
|
|
group_info = REDIS_CONN.queue_info(get_svr_queue_name(0), SVR_CONSUMER_GROUP_NAME)
|
2024-11-15 18:51:09 +08:00
|
|
|
if group_info is not None:
|
2024-12-13 17:31:15 +08:00
|
|
|
PENDING_TASKS = int(group_info.get("pending", 0))
|
|
|
|
LAG_TASKS = int(group_info.get("lag", 0))
|
2024-11-15 14:43:55 +08:00
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
current = copy.deepcopy(CURRENT_TASKS)
|
|
|
|
heartbeat = json.dumps({
|
|
|
|
"name": CONSUMER_NAME,
|
|
|
|
"now": now.astimezone().isoformat(timespec="milliseconds"),
|
|
|
|
"boot_at": BOOT_AT,
|
|
|
|
"pending": PENDING_TASKS,
|
|
|
|
"lag": LAG_TASKS,
|
|
|
|
"done": DONE_TASKS,
|
|
|
|
"failed": FAILED_TASKS,
|
|
|
|
"current": current,
|
|
|
|
})
|
2024-11-15 14:43:55 +08:00
|
|
|
REDIS_CONN.zadd(CONSUMER_NAME, heartbeat, now.timestamp())
|
|
|
|
logging.info(f"{CONSUMER_NAME} reported heartbeat: {heartbeat}")
|
|
|
|
|
2024-11-15 17:30:56 +08:00
|
|
|
expired = REDIS_CONN.zcount(CONSUMER_NAME, 0, now.timestamp() - 60 * 30)
|
2024-11-15 14:43:55 +08:00
|
|
|
if expired > 0:
|
|
|
|
REDIS_CONN.zpopmin(CONSUMER_NAME, expired)
|
2025-04-19 16:18:51 +08:00
|
|
|
|
|
|
|
# clean task executor
|
|
|
|
if redis_lock.acquire():
|
|
|
|
task_executors = REDIS_CONN.smembers("TASKEXE")
|
|
|
|
for consumer_name in task_executors:
|
|
|
|
if consumer_name == CONSUMER_NAME:
|
|
|
|
continue
|
|
|
|
expired = REDIS_CONN.zcount(
|
|
|
|
consumer_name, now.timestamp() - WORKER_HEARTBEAT_TIMEOUT, now.timestamp() + 10
|
|
|
|
)
|
|
|
|
if expired == 0:
|
|
|
|
logging.info(f"{consumer_name} expired, removed")
|
|
|
|
REDIS_CONN.srem("TASKEXE", consumer_name)
|
|
|
|
REDIS_CONN.delete(consumer_name)
|
2024-11-12 17:35:13 +08:00
|
|
|
except Exception:
|
2024-11-14 17:13:48 +08:00
|
|
|
logging.exception("report_status got exception")
|
2025-04-24 11:44:34 +08:00
|
|
|
finally:
|
|
|
|
redis_lock.release()
|
2025-03-03 18:59:49 +08:00
|
|
|
await trio.sleep(30)
|
|
|
|
|
|
|
|
|
2025-04-19 16:18:51 +08:00
|
|
|
def recover_pending_tasks():
|
|
|
|
redis_lock = RedisDistributedLock("recover_pending_tasks", lock_value=CONSUMER_NAME, timeout=60)
|
|
|
|
svr_queue_names = get_svr_queue_names()
|
|
|
|
while not stop_event.is_set():
|
|
|
|
try:
|
|
|
|
if redis_lock.acquire():
|
|
|
|
for queue_name in svr_queue_names:
|
|
|
|
msgs = REDIS_CONN.get_pending_msg(queue=queue_name, group_name=SVR_CONSUMER_GROUP_NAME)
|
|
|
|
msgs = [msg for msg in msgs if msg['consumer'] != CONSUMER_NAME]
|
|
|
|
if len(msgs) == 0:
|
|
|
|
continue
|
|
|
|
|
|
|
|
task_executors = REDIS_CONN.smembers("TASKEXE")
|
|
|
|
task_executor_set = {t for t in task_executors}
|
|
|
|
msgs = [msg for msg in msgs if msg['consumer'] not in task_executor_set]
|
|
|
|
for msg in msgs:
|
|
|
|
logging.info(
|
|
|
|
f"Recover pending task: {msg['message_id']}, consumer: {msg['consumer']}, "
|
|
|
|
f"time since delivered: {msg['time_since_delivered'] / 1000} s"
|
|
|
|
)
|
|
|
|
REDIS_CONN.requeue_msg(queue_name, SVR_CONSUMER_GROUP_NAME, msg['message_id'])
|
|
|
|
except Exception:
|
|
|
|
logging.warning("recover_pending_tasks got exception")
|
2025-04-24 11:44:34 +08:00
|
|
|
finally:
|
|
|
|
redis_lock.release()
|
2025-04-29 16:50:39 +08:00
|
|
|
stop_event.wait(60)
|
|
|
|
|
2025-05-19 10:25:56 +08:00
|
|
|
async def task_manager():
|
2025-06-06 03:32:35 -03:00
|
|
|
try:
|
2025-05-19 10:25:56 +08:00
|
|
|
await handle_task()
|
2025-06-06 03:32:35 -03:00
|
|
|
finally:
|
|
|
|
task_limiter.release()
|
2025-04-19 16:18:51 +08:00
|
|
|
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def main():
|
2024-11-30 18:48:06 +08:00
|
|
|
logging.info(r"""
|
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.
2025-04-18 18:00:20 +08:00
|
|
|
______ __ ______ __
|
2024-11-30 18:48:06 +08:00
|
|
|
/_ __/___ ______/ /__ / ____/ _____ _______ __/ /_____ _____
|
|
|
|
/ / / __ `/ ___/ //_/ / __/ | |/_/ _ \/ ___/ / / / __/ __ \/ ___/
|
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.
2025-04-18 18:00:20 +08:00
|
|
|
/ / / /_/ (__ ) ,< / /____> </ __/ /__/ /_/ / /_/ /_/ / /
|
|
|
|
/_/ \__,_/____/_/|_| /_____/_/|_|\___/\___/\__,_/\__/\____/_/
|
2024-11-30 18:48:06 +08:00
|
|
|
""")
|
|
|
|
logging.info(f'TaskExecutor: RAGFlow version: {get_ragflow_version()}')
|
2024-11-15 22:55:41 +08:00
|
|
|
settings.init_settings()
|
2024-11-30 18:48:06 +08:00
|
|
|
print_rag_settings()
|
2025-03-12 09:43:18 +08:00
|
|
|
if sys.platform != "win32":
|
|
|
|
signal.signal(signal.SIGUSR1, start_tracemalloc_and_snapshot)
|
|
|
|
signal.signal(signal.SIGUSR2, stop_tracemalloc)
|
2025-02-24 16:21:55 +08:00
|
|
|
TRACE_MALLOC_ENABLED = int(os.environ.get('TRACE_MALLOC_ENABLED', "0"))
|
|
|
|
if TRACE_MALLOC_ENABLED:
|
|
|
|
start_tracemalloc_and_snapshot(None, None)
|
|
|
|
|
2025-04-19 16:18:51 +08:00
|
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
signal.signal(signal.SIGTERM, signal_handler)
|
|
|
|
|
|
|
|
threading.Thread(name="RecoverPendingTask", target=recover_pending_tasks).start()
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
nursery.start_soon(report_status)
|
2025-04-19 16:18:51 +08:00
|
|
|
while not stop_event.is_set():
|
2025-06-06 03:32:35 -03:00
|
|
|
await task_limiter.acquire()
|
2025-05-19 10:25:56 +08:00
|
|
|
nursery.start_soon(task_manager)
|
2025-03-03 18:59:49 +08:00
|
|
|
logging.error("BUG!!! You should not reach here!!!")
|
2024-11-30 18:48:06 +08:00
|
|
|
|
2024-11-15 18:51:09 +08:00
|
|
|
if __name__ == "__main__":
|
2025-03-13 14:37:59 +08:00
|
|
|
faulthandler.enable()
|
2025-06-18 09:41:09 +08:00
|
|
|
init_root_logger(CONSUMER_NAME)
|
2025-03-03 18:59:49 +08:00
|
|
|
trio.run(main)
|