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.
2026-01-12 12:48:23 +08:00
import time
2026-01-20 13:29:37 +08:00
from common . misc_utils import thread_pool_exec
2026-01-12 12:48:23 +08:00
start_ts = time . time ( )
2025-12-09 19:23:14 +08:00
import asyncio
2025-11-10 12:51:39 +08:00
import socket
2025-10-14 14:14:52 +08:00
import concurrent
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
2025-03-03 10:26:45 +08:00
2025-11-12 12:03:41 +08:00
from api . db import PIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPES
2025-10-09 12:36:19 +08:00
from api . db . services . knowledgebase_service import KnowledgebaseService
from api . db . services . pipeline_operation_log_service import PipelineOperationLogService
2025-12-30 11:41:38 +08:00
from api . db . joint_services . memory_message_service import handle_save_to_memory_task
2025-11-04 11:51:12 +08:00
from common . connection_utils import timeout
2026-01-22 15:34:08 +08:00
from common . metadata_utils import turn2jsonschema , update_metadata_to
2025-11-05 14:14:38 +08:00
from rag . utils . base64_image import image2id
feat: Auto-disable Raptor for structured data (Issue #11653) (#11676)
### What problem does this PR solve?
Feature: This PR implements automatic Raptor disabling for structured
data files to address issue #11653.
**Problem**: Raptor was being applied to all file types, including
highly structured data like Excel files and tabular PDFs. This caused
unnecessary token inflation, higher computational costs, and larger
memory usage for data that already has organized semantic units.
**Solution**: Automatically skip Raptor processing for:
- Excel files (.xls, .xlsx, .xlsm, .xlsb)
- CSV files (.csv, .tsv)
- PDFs with tabular data (table parser or html4excel enabled)
**Benefits**:
- 82% faster processing for structured files
- 47% token reduction
- 52% memory savings
- Preserved data structure for downstream applications
**Usage Examples**:
```
# Excel file - automatically skipped
should_skip_raptor(".xlsx") # True
# CSV file - automatically skipped
should_skip_raptor(".csv") # True
# Tabular PDF - automatically skipped
should_skip_raptor(".pdf", parser_id="table") # True
# Regular PDF - Raptor runs normally
should_skip_raptor(".pdf", parser_id="naive") # False
# Override for special cases
should_skip_raptor(".xlsx", raptor_config={"auto_disable_for_structured_data": False}) # False
```
**Configuration**: Includes `auto_disable_for_structured_data` toggle
(default: true) to allow override for special use cases.
**Testing**: 44 comprehensive tests, 100% passing
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2025-12-03 04:02:29 -05:00
from rag . utils . raptor_utils import should_skip_raptor , get_skip_reason
2025-11-03 20:25:02 +08:00
from common . log_utils import init_root_logger
2025-11-03 17:25:06 +08:00
from common . config_utils import show_configs
2026-01-29 14:23:26 +08:00
from rag . graphrag . general . index import run_graphrag_for_kb
from rag . graphrag . utils import get_llm_cache , set_llm_cache , get_tags_from_cache , set_tags_to_cache
2025-12-17 16:50:36 +08:00
from rag . prompts . generator import keyword_extraction , question_proposal , content_tagging , run_toc_from_text , \
gen_metadata
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-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
2025-02-24 16:21:55 +08:00
import signal
2025-03-10 15:15:06 +08:00
import exceptiongroup
2025-03-13 14:37:59 +08:00
import faulthandler
2024-09-29 09:49:45 +08:00
import numpy as np
2024-12-12 16:38:03 +08:00
from peewee import DoesNotExist
2025-11-05 08:01:39 +08:00
from common . constants import LLMType , ParserType , PipelineTaskType
2024-01-17 20:20:42 +08:00
from api . db . services . document_service import DocumentService
2026-01-28 13:29:34 +08:00
from api . db . services . doc_metadata_service import DocMetadataService
2024-01-31 19:57:45 +08:00
from api . db . services . llm_service import LLMBundle
2025-10-09 12:36:19 +08:00
from api . db . services . task_service import TaskService , has_canceled , CANVAS_DEBUG_DOC_ID , GRAPH_RAPTOR_FAKE_DOC_ID
2024-09-29 09:49:45 +08:00
from api . db . services . file2document_service import File2DocumentService
2026-03-05 17:27:17 +08:00
from api . db . joint_services . tenant_model_service import get_model_config_by_type_and_name , get_tenant_default_model_by_type
2025-11-06 19:24:46 +08:00
from common . 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
2025-10-09 12:36:19 +08:00
from rag . nlp import search , rag_tokenizer , add_positions
2024-09-29 09:49:45 +08:00
from rag . raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
2025-11-03 08:50:05 +08:00
from common . token_utils import num_tokens_from_string , truncate
2025-04-19 16:18:51 +08:00
from rag . utils . redis_conn import REDIS_CONN , RedisDistributedLock
2026-01-29 14:23:26 +08:00
from rag . graphrag . utils import chat_limiter
2025-11-05 11:07:54 +08:00
from common . signal_utils import start_tracemalloc_and_snapshot , stop_tracemalloc
2025-11-06 16:12:20 +08:00
from common . exceptions import TaskCanceledException
2025-11-06 09:36:38 +08:00
from common import settings
from common . constants import PAGERANK_FLD , TAG_FLD , SVR_CONSUMER_GROUP_NAME
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-10-09 12:36:19 +08:00
TASK_TYPE_TO_PIPELINE_TASK_TYPE = {
2025-12-29 12:01:18 +08:00
" dataflow " : PipelineTaskType . PARSE ,
2025-10-09 12:36:19 +08:00
" raptor " : PipelineTaskType . RAPTOR ,
" graphrag " : PipelineTaskType . GRAPH_RAG ,
" mindmap " : PipelineTaskType . MINDMAP ,
2025-12-30 11:41:38 +08:00
" memory " : PipelineTaskType . MEMORY ,
2025-10-09 12:36:19 +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-12-09 19:23:14 +08:00
task_limiter = asyncio . Semaphore ( MAX_CONCURRENT_TASKS )
chunk_limiter = asyncio . Semaphore ( MAX_CONCURRENT_CHUNK_BUILDERS )
embed_limiter = asyncio . Semaphore ( MAX_CONCURRENT_CHUNK_BUILDERS )
minio_limiter = asyncio . Semaphore ( MAX_CONCURRENT_MINIO )
kg_limiter = asyncio . Semaphore ( 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
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
2025-07-15 17:19:27 +08:00
cancel = has_canceled ( task_id )
2025-03-13 14:37:59 +08:00
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 } " )
2026-02-06 14:48:24 +08:00
except TaskCanceledException :
raise
2025-03-13 14:37:59 +08:00
except DoesNotExist :
logging . warning ( f " set_progress( { task_id } ) got exception DoesNotExist " )
2025-12-30 11:09:18 +08:00
except Exception as e :
logging . exception ( f " set_progress( { task_id } ), progress: { prog } , progress_msg: { msg } , got exception: { e } " )
2024-01-15 08:46:22 +08:00
2025-07-21 15:56:45 +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-11-06 09:36:38 +08:00
svr_queue_names = settings . get_svr_queue_names ( )
2025-12-30 11:09:18 +08:00
redis_msg = None
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
2025-12-30 11:09:18 +08:00
except Exception as e :
logging . exception ( f " collect got exception: { e } " )
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-10-09 12:36:19 +08:00
if msg . get ( " doc_id " , " " ) in [ GRAPH_RAPTOR_FAKE_DOC_ID , CANVAS_DEBUG_DOC_ID ] :
task = msg
2025-11-12 12:03:41 +08:00
if task [ " task_type " ] in PIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPES :
2025-10-09 12:36:19 +08:00
task = TaskService . get_task ( msg [ " id " ] , msg [ " doc_ids " ] )
2025-11-03 19:59:18 +08:00
if task :
task [ " doc_id " ] = msg [ " doc_id " ]
task [ " doc_ids " ] = msg . get ( " doc_ids " , [ ] ) or [ ]
2025-12-30 11:41:38 +08:00
elif msg . get ( " task_type " ) == PipelineTaskType . MEMORY . lower ( ) :
_ , task_obj = TaskService . get_by_id ( msg [ " id " ] )
task = task_obj . to_dict ( )
2025-10-09 12:36:19 +08:00
else :
task = TaskService . get_task ( msg [ " id " ] )
2025-03-03 18:59:49 +08:00
if task :
2025-07-15 17:19:27 +08:00
canceled = has_canceled ( task [ " id " ] )
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-09-05 18:50:46 +08:00
task_type = msg . get ( " task_type " , " " )
task [ " task_type " ] = task_type
2025-10-09 12:36:19 +08:00
if task_type [ : 8 ] == " dataflow " :
task [ " tenant_id " ] = msg [ " tenant_id " ]
task [ " dataflow_id " ] = msg [ " dataflow_id " ]
2025-09-05 18:50:46 +08:00
task [ " kb_id " ] = msg . get ( " kb_id " , " " )
2025-12-30 11:41:38 +08:00
if task_type [ : 6 ] == " memory " :
task [ " memory_id " ] = msg [ " memory_id " ]
task [ " source_id " ] = msg [ " source_id " ]
task [ " message_dict " ] = msg [ " message_dict " ]
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 ) :
2026-01-20 13:29:37 +08:00
return await thread_pool_exec ( settings . STORAGE_IMPL . get , bucket , name )
2024-04-08 19:20:57 +08:00
2024-01-15 08:46:22 +08:00
2025-12-29 12:01:18 +08:00
@timeout ( 60 * 80 , 1 )
2025-03-03 18:59:49 +08:00
async def build_chunks ( task , progress_callback ) :
2025-11-06 09:36:38 +08:00
if task [ " size " ] > settings . DOC_MAXIMUM_SIZE :
2024-12-01 22:28:00 +08:00
set_progress ( task [ " id " ] , prog = - 1 , msg = " File size exceeds( <= %d Mb ) " %
2025-11-06 09:36:38 +08:00
( int ( settings . 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 :
2026-01-20 13:29:37 +08:00
cks = await thread_pool_exec (
2025-12-09 19:23:14 +08:00
chunker . chunk ,
task [ " name " ] ,
binary = binary ,
from_page = task [ " from_page " ] ,
to_page = task [ " to_page " ] ,
lang = task [ " language " ] ,
callback = progress_callback ,
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-07-15 09:36:45 +08:00
@timeout ( 60 )
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 )
2025-12-29 12:01:18 +08:00
d [ " id " ] = xxhash . xxh64 (
( chunk [ " content_with_weight " ] + str ( d [ " doc_id " ] ) ) . encode ( " utf-8 " , " surrogatepass " ) ) . hexdigest ( )
2025-05-27 17:49:37 +08:00
d [ " create_time " ] = str ( datetime . now ( ) ) . replace ( " T " , " " ) [ : 19 ]
d [ " create_timestamp_flt " ] = datetime . now ( ) . timestamp ( )
2026-01-13 12:54:13 +08:00
if d . get ( " img_id " ) :
docs . append ( d )
return
2025-05-27 17:49:37 +08:00
if not d . get ( " image " ) :
_ = d . pop ( " image " , None )
d [ " img_id " ] = " "
docs . append ( d )
return
2025-11-06 09:36:38 +08:00
await image2id ( d , partial ( settings . STORAGE_IMPL . put , tenant_id = task [ " tenant_id " ] ) , d [ " id " ] , task [ " kb_id " ] )
2025-10-09 12:36:19 +08:00
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-12-09 19:23:14 +08:00
tasks = [ ]
for ck in cks :
tasks . append ( asyncio . create_task ( upload_to_minio ( doc , ck ) ) )
try :
await asyncio . gather ( * tasks , return_exceptions = False )
except Exception as e :
logging . error ( f " MINIO PUT( { task [ ' name ' ] } ) got exception: { e } " )
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
raise
2025-05-06 14:39:45 +08:00
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 ... " )
2026-03-05 17:27:17 +08:00
chat_model_config = get_model_config_by_type_and_name ( task [ " tenant_id " ] , LLMType . CHAT , task [ " llm_id " ] )
chat_mdl = LLMBundle ( task [ " tenant_id " ] , chat_model_config , 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-12-30 20:24:27 +08:00
if has_canceled ( task [ " id " ] ) :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return
2025-03-03 18:59:49 +08:00
async with chat_limiter :
2025-12-11 17:38:17 +08:00
cached = await 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-12-29 12:01:18 +08:00
2025-12-09 19:23:14 +08:00
tasks = [ ]
for d in docs :
2025-12-29 12:01:18 +08:00
tasks . append (
asyncio . create_task ( doc_keyword_extraction ( chat_mdl , d , task [ " parser_config " ] [ " auto_keywords " ] ) ) )
2025-12-09 19:23:14 +08:00
try :
await asyncio . gather ( * tasks , return_exceptions = False )
except Exception as e :
logging . error ( " Error in doc_keyword_extraction: {} " . format ( e ) )
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
raise
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 ... " )
2026-03-05 17:27:17 +08:00
chat_model_config = get_model_config_by_type_and_name ( task [ " tenant_id " ] , LLMType . CHAT , task [ " llm_id " ] )
chat_mdl = LLMBundle ( task [ " tenant_id " ] , chat_model_config , 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-12-30 20:24:27 +08:00
if has_canceled ( task [ " id " ] ) :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return
2025-03-03 18:59:49 +08:00
async with chat_limiter :
2025-12-11 17:38:17 +08:00
cached = await 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-12-29 12:01:18 +08:00
2025-12-09 19:23:14 +08:00
tasks = [ ]
for d in docs :
2025-12-29 12:01:18 +08:00
tasks . append (
asyncio . create_task ( doc_question_proposal ( chat_mdl , d , task [ " parser_config " ] [ " auto_questions " ] ) ) )
2025-12-09 19:23:14 +08:00
try :
await asyncio . gather ( * tasks , return_exceptions = False )
except Exception as e :
logging . error ( " Error in doc_question_proposal " , exc_info = e )
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
raise
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-12-17 16:50:36 +08:00
if task [ " parser_config " ] . get ( " enable_metadata " , False ) and task [ " parser_config " ] . get ( " metadata " ) :
st = timer ( )
progress_callback ( msg = " Start to generate meta-data for every chunk ... " )
2026-03-05 17:27:17 +08:00
chat_model_config = get_model_config_by_type_and_name ( task [ " tenant_id " ] , LLMType . CHAT , task [ " llm_id " ] )
chat_mdl = LLMBundle ( task [ " tenant_id " ] , chat_model_config , lang = task [ " language " ] )
2025-12-17 16:50:36 +08:00
async def gen_metadata_task ( chat_mdl , d ) :
2025-12-29 12:01:18 +08:00
cached = get_llm_cache ( chat_mdl . llm_name , d [ " content_with_weight " ] , " metadata " ,
task [ " parser_config " ] [ " metadata " ] )
2025-12-17 16:50:36 +08:00
if not cached :
2025-12-30 20:24:27 +08:00
if has_canceled ( task [ " id " ] ) :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return
2025-12-17 16:50:36 +08:00
async with chat_limiter :
cached = await gen_metadata ( chat_mdl ,
2026-01-22 15:34:08 +08:00
turn2jsonschema ( task [ " parser_config " ] [ " metadata " ] ) ,
2025-12-17 16:50:36 +08:00
d [ " content_with_weight " ] )
2025-12-29 12:01:18 +08:00
set_llm_cache ( chat_mdl . llm_name , d [ " content_with_weight " ] , cached , " metadata " ,
task [ " parser_config " ] [ " metadata " ] )
2025-12-17 16:50:36 +08:00
if cached :
d [ " metadata_obj " ] = cached
2025-12-29 12:01:18 +08:00
2025-12-17 16:50:36 +08:00
tasks = [ ]
for d in docs :
tasks . append ( asyncio . create_task ( gen_metadata_task ( chat_mdl , d ) ) )
try :
await asyncio . gather ( * tasks , return_exceptions = False )
except Exception as e :
logging . error ( " Error in doc_question_proposal " , exc_info = e )
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
raise
metadata = { }
2025-12-24 09:32:19 +08:00
for doc in docs :
metadata = update_metadata_to ( metadata , doc [ " metadata_obj " ] )
2025-12-24 13:40:34 +08:00
del doc [ " metadata_obj " ]
2025-12-17 16:50:36 +08:00
if metadata :
2026-01-28 13:29:34 +08:00
existing_meta = DocMetadataService . get_document_metadata ( task [ " doc_id " ] )
existing_meta = existing_meta if isinstance ( existing_meta , dict ) else { }
metadata = update_metadata_to ( metadata , existing_meta )
DocMetadataService . update_document_metadata ( task [ " doc_id " ] , metadata )
2025-12-17 16:50:36 +08:00
progress_callback ( msg = " Question generation {} chunks completed in {:.2f} s " . format ( len ( docs ) , timer ( ) - st ) )
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 :
2025-11-06 09:36:38 +08:00
all_tags = settings . retriever . all_tags_in_portion ( tenant_id , kb_ids , S )
2025-01-09 17:07:21 +08:00
set_tags_to_cache ( kb_ids , all_tags )
else :
all_tags = json . loads ( all_tags )
2026-03-05 17:27:17 +08:00
chat_model_config = get_model_config_by_type_and_name ( tenant_id , LLMType . CHAT , task [ " llm_id " ] )
chat_mdl = LLMBundle ( task [ " tenant_id " ] , chat_model_config , 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-07-15 17:19:27 +08:00
task_canceled = has_canceled ( task [ " id " ] )
2025-05-22 09:28:08 +08:00
if task_canceled :
progress_callback ( - 1 , msg = " Task has been canceled. " )
2025-11-12 19:00:15 +08:00
return None
2025-12-29 12:01:18 +08:00
if settings . retriever . 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-12-30 20:24:27 +08:00
if has_canceled ( task [ " id " ] ) :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return
2025-12-29 12:01:18 +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 :
2025-12-11 17:38:17 +08:00
cached = await content_tagging (
2025-12-09 19:23:14 +08:00
chat_mdl ,
d [ " content_with_weight " ] ,
all_tags ,
picked_examples ,
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-12-29 12:01:18 +08:00
2025-12-09 19:23:14 +08:00
tasks = [ ]
for d in docs_to_tag :
tasks . append ( asyncio . create_task ( doc_content_tagging ( chat_mdl , d , topn_tags ) ) )
try :
await asyncio . gather ( * tasks , return_exceptions = False )
except Exception as e :
logging . error ( " Error tagging docs: {} " . format ( e ) )
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
raise
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
2025-10-14 14:14:52 +08:00
def build_TOC ( task , docs , progress_callback ) :
progress_callback ( msg = " Start to generate table of content ... " )
2026-03-05 17:27:17 +08:00
chat_model_config = get_model_config_by_type_and_name ( task [ " tenant_id " ] , LLMType . CHAT , task [ " llm_id " ] )
chat_mdl = LLMBundle ( task [ " tenant_id " ] , chat_model_config , lang = task [ " language " ] )
2025-12-29 12:01:18 +08:00
docs = sorted ( docs , key = lambda d : (
2025-10-14 14:14:52 +08:00
d . get ( " page_num_int " , 0 ) [ 0 ] if isinstance ( d . get ( " page_num_int " , 0 ) , list ) else d . get ( " page_num_int " , 0 ) ,
d . get ( " top_int " , 0 ) [ 0 ] if isinstance ( d . get ( " top_int " , 0 ) , list ) else d . get ( " top_int " , 0 )
) )
2025-12-29 12:01:18 +08:00
toc : list [ dict ] = asyncio . run (
run_toc_from_text ( [ d [ " content_with_weight " ] for d in docs ] , chat_mdl , progress_callback ) )
logging . info ( " ------------ T O C ------------- \n " + json . dumps ( toc , ensure_ascii = False , indent = ' ' ) )
2026-01-05 10:02:42 +08:00
for ii , item in enumerate ( toc ) :
2025-10-14 14:14:52 +08:00
try :
2026-01-05 10:02:42 +08:00
chunk_val = item . pop ( " chunk_id " , None )
if chunk_val is None or str ( chunk_val ) . strip ( ) == " " :
logging . warning ( f " Index { ii } : chunk_id is missing or empty. Skipping. " )
continue
curr_idx = int ( chunk_val )
if curr_idx > = len ( docs ) :
logging . error ( f " Index { ii } : chunk_id { curr_idx } exceeds docs length { len ( docs ) } . " )
continue
item [ " ids " ] = [ docs [ curr_idx ] [ " id " ] ]
if ii + 1 < len ( toc ) :
next_chunk_val = toc [ ii + 1 ] . get ( " chunk_id " , " " )
if str ( next_chunk_val ) . strip ( ) != " " :
next_idx = int ( next_chunk_val )
for jj in range ( curr_idx + 1 , min ( next_idx + 1 , len ( docs ) ) ) :
item [ " ids " ] . append ( docs [ jj ] [ " id " ] )
else :
logging . warning ( f " Index { ii + 1 } : next chunk_id is empty, range fill skipped. " )
except ( ValueError , TypeError ) as e :
logging . error ( f " Index { ii } : Data conversion error - { e } " )
2025-10-14 14:14:52 +08:00
except Exception as e :
2026-01-05 10:02:42 +08:00
logging . exception ( f " Index { ii } : Unexpected error - { e } " )
2025-10-14 14:14:52 +08:00
if toc :
d = copy . deepcopy ( docs [ - 1 ] )
d [ " content_with_weight " ] = json . dumps ( toc , ensure_ascii = False )
d [ " toc_kwd " ] = " toc "
d [ " available_int " ] = 0
2025-10-16 12:47:24 +08:00
d [ " page_num_int " ] = [ 100000000 ]
2025-12-29 12:01:18 +08:00
d [ " id " ] = xxhash . xxh64 (
( d [ " content_with_weight " ] + str ( d [ " doc_id " ] ) ) . encode ( " utf-8 " , " surrogatepass " ) ) . hexdigest ( )
2025-10-14 14:14:52 +08:00
return d
2025-11-12 19:00:15 +08:00
return None
2025-10-14 14:14:52 +08:00
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 " ] )
2026-01-19 19:35:14 +08:00
parser_id = row . get ( " parser_id " , None )
return settings . docStoreConn . create_idx ( idxnm , row . get ( " kb_id " , " " ) , vector_size , parser_id )
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 ) :
2026-01-20 13:29:37 +08:00
vts , c = await thread_pool_exec ( mdl . encode , tts [ 0 : 1 ] )
2025-11-13 18:48:25 +08:00
tts = np . tile ( vts [ 0 ] , ( len ( cnts ) , 1 ) )
2025-01-15 15:20:29 +08:00
tk_count + = c
2024-02-01 18:53:56 +08:00
2025-08-12 14:12:56 +08:00
@timeout ( 60 )
2025-08-05 19:24:34 +08:00
def batch_encode ( txts ) :
nonlocal mdl
2025-12-29 12:01:18 +08:00
return mdl . encode ( [ truncate ( c , mdl . max_length - 10 ) for c in txts ] )
2025-08-05 19:24:34 +08:00
2024-03-05 16:33:47 +08:00
cnts_ = np . array ( [ ] )
2025-11-06 09:36:38 +08:00
for i in range ( 0 , len ( cnts ) , settings . EMBEDDING_BATCH_SIZE ) :
2025-07-23 10:17:04 +08:00
async with embed_limiter :
2026-01-20 13:29:37 +08:00
vts , c = await thread_pool_exec ( batch_encode , cnts [ i : i + settings . 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_
2025-12-29 12:01:18 +08:00
filename_embd_weight = parser_config . get ( " filename_embd_weight " , 0.1 ) # due to the db support none value
2025-07-04 12:41:28 +08:00
if not filename_embd_weight :
filename_embd_weight = 0.1
title_w = float ( filename_embd_weight )
2025-11-13 18:48:25 +08:00
if tts . ndim == 2 and cnts . ndim == 2 and tts . shape == cnts . shape :
vects = title_w * tts + ( 1 - title_w ) * cnts
else :
vects = 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-10-09 12:36:19 +08:00
async def run_dataflow ( task : dict ) :
2025-11-11 17:36:48 +08:00
from api . db . services . canvas_service import UserCanvasService
from rag . flow . pipeline import Pipeline
2025-10-09 12:36:19 +08:00
task_start_ts = timer ( )
dataflow_id = task [ " dataflow_id " ]
doc_id = task [ " doc_id " ]
task_id = task [ " id " ]
task_dataset_id = task [ " kb_id " ]
if task [ " task_type " ] == " dataflow " :
e , cvs = UserCanvasService . get_by_id ( dataflow_id )
assert e , " User pipeline not found. "
dsl = cvs . dsl
else :
e , pipeline_log = PipelineOperationLogService . get_by_id ( dataflow_id )
assert e , " Pipeline log not found. "
dsl = pipeline_log . dsl
dataflow_id = pipeline_log . pipeline_id
pipeline = Pipeline ( dsl , tenant_id = task [ " tenant_id " ] , doc_id = doc_id , task_id = task_id , flow_id = dataflow_id )
chunks = await pipeline . run ( file = task [ " file " ] ) if task . get ( " file " ) else await pipeline . run ( )
if doc_id == CANVAS_DEBUG_DOC_ID :
return
if not chunks :
2025-12-29 12:01:18 +08:00
PipelineOperationLogService . create ( document_id = doc_id , pipeline_id = dataflow_id ,
task_type = PipelineTaskType . PARSE , dsl = str ( pipeline ) )
2025-10-09 12:36:19 +08:00
return
embedding_token_consumption = chunks . get ( " embedding_token_consumption " , 0 )
if chunks . get ( " chunks " ) :
chunks = copy . deepcopy ( chunks [ " chunks " ] )
elif chunks . get ( " json " ) :
chunks = copy . deepcopy ( chunks [ " json " ] )
elif chunks . get ( " markdown " ) :
chunks = [ { " text " : [ chunks [ " markdown " ] ] } ]
elif chunks . get ( " text " ) :
chunks = [ { " text " : [ chunks [ " text " ] ] } ]
elif chunks . get ( " html " ) :
chunks = [ { " text " : [ chunks [ " html " ] ] } ]
keys = [ k for o in chunks for k in list ( o . keys ( ) ) ]
if not any ( [ re . match ( r " q_[0-9]+_vec " , k ) for k in keys ] ) :
try :
set_progress ( task_id , prog = 0.82 , msg = " \n ------------------------------------- \n Start to embedding... " )
e , kb = KnowledgebaseService . get_by_id ( task [ " kb_id " ] )
embedding_id = kb . embd_id
2026-03-05 17:27:17 +08:00
embd_model_config = get_model_config_by_type_and_name ( task [ " tenant_id " ] , LLMType . EMBEDDING , embedding_id )
embedding_model = LLMBundle ( task [ " tenant_id " ] , embd_model_config )
2025-12-29 12:01:18 +08:00
2025-10-09 12:36:19 +08:00
@timeout ( 60 )
def batch_encode ( txts ) :
nonlocal embedding_model
return embedding_model . encode ( [ truncate ( c , embedding_model . max_length - 10 ) for c in txts ] )
2025-12-29 12:01:18 +08:00
2025-10-09 12:36:19 +08:00
vects = np . array ( [ ] )
texts = [ o . get ( " questions " , o . get ( " summary " , o [ " text " ] ) ) for o in chunks ]
2025-12-29 12:01:18 +08:00
delta = 0.20 / ( len ( texts ) / / settings . EMBEDDING_BATCH_SIZE + 1 )
2025-10-09 12:36:19 +08:00
prog = 0.8
2025-11-06 09:36:38 +08:00
for i in range ( 0 , len ( texts ) , settings . EMBEDDING_BATCH_SIZE ) :
2025-10-09 12:36:19 +08:00
async with embed_limiter :
2026-01-20 13:29:37 +08:00
vts , c = await thread_pool_exec ( batch_encode , texts [ i : i + settings . EMBEDDING_BATCH_SIZE ] )
2025-10-09 12:36:19 +08:00
if len ( vects ) == 0 :
vects = vts
else :
vects = np . concatenate ( ( vects , vts ) , axis = 0 )
embedding_token_consumption + = c
prog + = delta
2025-12-29 12:01:18 +08:00
if i % ( len ( texts ) / / settings . EMBEDDING_BATCH_SIZE / 100 + 1 ) == 1 :
set_progress ( task_id , prog = prog , msg = f " { i + 1 } / { len ( texts ) / / settings . EMBEDDING_BATCH_SIZE } " )
2025-10-09 12:36:19 +08:00
assert len ( vects ) == len ( chunks )
for i , ck in enumerate ( chunks ) :
v = vects [ i ] . tolist ( )
ck [ " q_ %d _vec " % len ( v ) ] = v
2026-02-06 14:48:24 +08:00
except TaskCanceledException :
raise
2025-10-09 12:36:19 +08:00
except Exception as e :
set_progress ( task_id , prog = - 1 , msg = f " [ERROR]: { e } " )
2025-12-29 12:01:18 +08:00
PipelineOperationLogService . create ( document_id = doc_id , pipeline_id = dataflow_id ,
task_type = PipelineTaskType . PARSE , dsl = str ( pipeline ) )
2025-10-09 12:36:19 +08:00
return
metadata = { }
for ck in chunks :
ck [ " doc_id " ] = doc_id
ck [ " kb_id " ] = [ str ( task [ " kb_id " ] ) ]
ck [ " docnm_kwd " ] = task [ " name " ]
ck [ " create_time " ] = str ( datetime . now ( ) ) . replace ( " T " , " " ) [ : 19 ]
ck [ " create_timestamp_flt " ] = datetime . now ( ) . timestamp ( )
2025-12-08 09:42:20 +08:00
if not ck . get ( " id " ) :
ck [ " id " ] = xxhash . xxh64 ( ( ck [ " text " ] + str ( ck [ " doc_id " ] ) ) . encode ( " utf-8 " ) ) . hexdigest ( )
2025-10-09 12:36:19 +08:00
if " questions " in ck :
if " question_tks " not in ck :
ck [ " question_kwd " ] = ck [ " questions " ] . split ( " \n " )
ck [ " question_tks " ] = rag_tokenizer . tokenize ( str ( ck [ " questions " ] ) )
del ck [ " questions " ]
if " keywords " in ck :
if " important_tks " not in ck :
ck [ " important_kwd " ] = ck [ " keywords " ] . split ( " , " )
ck [ " important_tks " ] = rag_tokenizer . tokenize ( str ( ck [ " keywords " ] ) )
del ck [ " keywords " ]
if " summary " in ck :
if " content_ltks " not in ck :
ck [ " content_ltks " ] = rag_tokenizer . tokenize ( str ( ck [ " summary " ] ) )
ck [ " content_sm_ltks " ] = rag_tokenizer . fine_grained_tokenize ( ck [ " content_ltks " ] )
del ck [ " summary " ]
if " metadata " in ck :
2025-12-17 16:50:36 +08:00
metadata = update_metadata_to ( metadata , ck [ " metadata " ] )
2025-10-09 12:36:19 +08:00
del ck [ " metadata " ]
if " content_with_weight " not in ck :
ck [ " content_with_weight " ] = ck [ " text " ]
del ck [ " text " ]
if " positions " in ck :
add_positions ( ck , ck [ " positions " ] )
del ck [ " positions " ]
if metadata :
2026-01-28 13:29:34 +08:00
existing_meta = DocMetadataService . get_document_metadata ( doc_id )
existing_meta = existing_meta if isinstance ( existing_meta , dict ) else { }
metadata = update_metadata_to ( metadata , existing_meta )
DocMetadataService . update_document_metadata ( doc_id , metadata )
2025-09-05 18:50:46 +08:00
2025-10-09 12:36:19 +08:00
start_ts = timer ( )
set_progress ( task_id , prog = 0.82 , msg = " [DOC Engine]: \n Start to index... " )
2026-01-19 19:35:14 +08:00
e = await insert_chunks ( task_id , task [ " tenant_id " ] , task [ " kb_id " ] , chunks , partial ( set_progress , task_id , 0 , 100000000 ) )
2025-10-09 12:36:19 +08:00
if not e :
2025-12-29 12:01:18 +08:00
PipelineOperationLogService . create ( document_id = doc_id , pipeline_id = dataflow_id ,
task_type = PipelineTaskType . PARSE , dsl = str ( pipeline ) )
2025-10-09 12:36:19 +08:00
return
2025-09-05 18:50:46 +08:00
2025-10-09 12:36:19 +08:00
time_cost = timer ( ) - start_ts
task_time_cost = timer ( ) - task_start_ts
set_progress ( task_id , prog = 1. , msg = " Indexing done ( {:.2f} s). Task done ( {:.2f} s) " . format ( time_cost , task_time_cost ) )
2025-12-29 12:01:18 +08:00
DocumentService . increment_chunk_num ( doc_id , task_dataset_id , embedding_token_consumption , len ( chunks ) ,
task_time_cost )
logging . info ( " [Done], chunks( {} ), token( {} ), elapsed: {:.2f} " . format ( len ( chunks ) , embedding_token_consumption ,
task_time_cost ) )
PipelineOperationLogService . create ( document_id = doc_id , pipeline_id = dataflow_id , task_type = PipelineTaskType . PARSE ,
dsl = str ( pipeline ) )
2025-09-05 18:50:46 +08:00
2025-07-15 09:36:45 +08:00
@timeout ( 3600 )
2025-10-09 12:36:19 +08:00
async def run_raptor_for_kb ( row , kb_parser_config , chat_mdl , embd_mdl , vector_size , callback = None , doc_ids = [ ] ) :
fake_doc_id = GRAPH_RAPTOR_FAKE_DOC_ID
raptor_config = kb_parser_config . get ( " raptor " , { } )
2025-12-29 12:01:18 +08:00
vctr_nm = " q_ %d _vec " % vector_size
2025-11-11 16:58:47 +08:00
2024-05-23 14:31:16 +08:00
res = [ ]
tk_count = 0
2025-11-13 18:48:07 +08:00
max_errors = int ( os . environ . get ( " RAPTOR_MAX_ERRORS " , 3 ) )
2026-03-10 14:24:33 +08:00
doc_name_by_id = { }
for doc_id in set ( doc_ids ) :
ok , source_doc = DocumentService . get_by_id ( doc_id )
if not ok or not source_doc :
continue
source_name = getattr ( source_doc , " name " , " " )
if source_name :
doc_name_by_id [ doc_id ] = source_name
2025-11-13 18:48:07 +08:00
2025-11-11 19:46:41 +08:00
async def generate ( chunks , did ) :
2025-11-11 16:58:47 +08:00
nonlocal tk_count , res
raptor = Raptor (
raptor_config . get ( " max_cluster " , 64 ) ,
chat_mdl ,
embd_mdl ,
raptor_config [ " prompt " ] ,
raptor_config [ " max_token " ] ,
raptor_config [ " threshold " ] ,
2025-11-13 18:48:07 +08:00
max_errors = max_errors ,
2025-11-11 16:58:47 +08:00
)
original_length = len ( chunks )
chunks = await raptor ( chunks , kb_parser_config [ " raptor " ] [ " random_seed " ] , callback , row [ " id " ] )
2026-03-10 14:24:33 +08:00
effective_doc_name = row [ " name " ] if did == fake_doc_id else doc_name_by_id . get ( did , row [ " name " ] )
2025-11-11 16:58:47 +08:00
doc = {
2025-11-11 19:46:41 +08:00
" doc_id " : did ,
2025-11-11 16:58:47 +08:00
" kb_id " : [ str ( row [ " kb_id " ] ) ] ,
2026-03-10 14:24:33 +08:00
" docnm_kwd " : effective_doc_name ,
" title_tks " : rag_tokenizer . tokenize ( effective_doc_name ) ,
2025-11-11 16:58:47 +08:00
" raptor_kwd " : " raptor "
}
if row [ " pagerank " ] :
doc [ PAGERANK_FLD ] = int ( row [ " pagerank " ] )
for content , vctr in chunks [ original_length : ] :
d = copy . deepcopy ( doc )
d [ " id " ] = xxhash . xxh64 ( ( content + str ( fake_doc_id ) ) . encode ( " utf-8 " ) ) . hexdigest ( )
d [ " create_time " ] = str ( datetime . now ( ) ) . replace ( " T " , " " ) [ : 19 ]
d [ " create_timestamp_flt " ] = datetime . now ( ) . timestamp ( )
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 )
if raptor_config . get ( " scope " , " file " ) == " file " :
for x , doc_id in enumerate ( doc_ids ) :
chunks = [ ]
2026-01-20 15:24:20 +11:00
skipped_chunks = 0
2025-11-11 16:58:47 +08:00
for d in settings . retriever . chunk_list ( doc_id , row [ " tenant_id " ] , [ str ( row [ " kb_id " ] ) ] ,
2025-12-29 12:01:18 +08:00
fields = [ " content_with_weight " , vctr_nm ] ,
sort_by_position = True ) :
2026-01-20 15:24:20 +11:00
# Skip chunks that don't have the required vector field (may have been indexed with different embedding model)
if vctr_nm not in d or d [ vctr_nm ] is None :
skipped_chunks + = 1
logging . warning ( f " RAPTOR: Chunk missing vector field ' { vctr_nm } ' in doc { doc_id } , skipping " )
continue
2025-11-11 16:58:47 +08:00
chunks . append ( ( d [ " content_with_weight " ] , np . array ( d [ vctr_nm ] ) ) )
2026-01-20 15:24:20 +11:00
if skipped_chunks > 0 :
callback ( msg = f " [WARN] Skipped { skipped_chunks } chunks without vector field ' { vctr_nm } ' for doc { doc_id } . Consider re-parsing the document with the current embedding model. " )
if not chunks :
logging . warning ( f " RAPTOR: No valid chunks with vectors found for doc { doc_id } " )
callback ( msg = f " [WARN] No valid chunks with vectors found for doc { doc_id } , skipping " )
continue
2025-11-11 19:46:41 +08:00
await generate ( chunks , doc_id )
2025-12-29 12:01:18 +08:00
callback ( prog = ( x + 1. ) / len ( doc_ids ) )
2025-11-11 16:58:47 +08:00
else :
chunks = [ ]
2026-01-20 15:24:20 +11:00
skipped_chunks = 0
2025-11-11 16:58:47 +08:00
for doc_id in doc_ids :
for d in settings . retriever . chunk_list ( doc_id , row [ " tenant_id " ] , [ str ( row [ " kb_id " ] ) ] ,
2025-12-29 12:01:18 +08:00
fields = [ " content_with_weight " , vctr_nm ] ,
sort_by_position = True ) :
2026-01-20 15:24:20 +11:00
# Skip chunks that don't have the required vector field
if vctr_nm not in d or d [ vctr_nm ] is None :
skipped_chunks + = 1
logging . warning ( f " RAPTOR: Chunk missing vector field ' { vctr_nm } ' in doc { doc_id } , skipping " )
continue
2025-11-11 16:58:47 +08:00
chunks . append ( ( d [ " content_with_weight " ] , np . array ( d [ vctr_nm ] ) ) )
2026-01-20 15:24:20 +11:00
if skipped_chunks > 0 :
callback ( msg = f " [WARN] Skipped { skipped_chunks } chunks without vector field ' { vctr_nm } ' . Consider re-parsing documents with the current embedding model. " )
if not chunks :
logging . error ( f " RAPTOR: No valid chunks with vectors found in any document for kb { row [ ' kb_id ' ] } " )
callback ( msg = f " [ERROR] No valid chunks with vectors found. Please ensure documents are parsed with the current embedding model (vector size: { vector_size } ). " )
return res , tk_count
2025-11-11 19:46:41 +08:00
await generate ( chunks , fake_doc_id )
2025-11-11 16:58:47 +08:00
2025-01-22 19:43:14 +08:00
return res , tk_count
2025-10-09 12:36:19 +08:00
async def delete_image ( kb_id , chunk_id ) :
try :
async with minio_limiter :
2025-11-06 09:36:38 +08:00
settings . STORAGE_IMPL . delete ( kb_id , chunk_id )
2025-10-09 12:36:19 +08:00
except Exception :
logging . exception ( f " Deleting image of chunk { chunk_id } got exception " )
raise
2026-01-19 19:35:14 +08:00
async def insert_chunks ( task_id , task_tenant_id , task_dataset_id , chunks , progress_callback ) :
"""
Insert chunks into document store ( Elasticsearch OR Infinity ) .
Args :
task_id : Task identifier
task_tenant_id : Tenant ID
task_dataset_id : Dataset / knowledge base ID
chunks : List of chunk dictionaries to insert
progress_callback : Callback function for progress updates
"""
2025-11-28 19:25:32 +08:00
mothers = [ ]
mother_ids = set ( [ ] )
for ck in chunks :
mom = ck . get ( " mom " ) or ck . get ( " mom_with_weight " ) or " "
if not mom :
continue
id = xxhash . xxh64 ( mom . encode ( " utf-8 " ) ) . hexdigest ( )
2025-12-09 09:34:01 +08:00
ck [ " mom_id " ] = id
2025-11-28 19:25:32 +08:00
if id in mother_ids :
continue
mother_ids . add ( id )
mom_ck = copy . deepcopy ( ck )
mom_ck [ " id " ] = id
mom_ck [ " content_with_weight " ] = mom
mom_ck [ " available_int " ] = 0
flds = list ( mom_ck . keys ( ) )
for fld in flds :
2025-12-29 12:01:18 +08:00
if fld not in [ " id " , " content_with_weight " , " doc_id " , " docnm_kwd " , " kb_id " , " available_int " ,
fix: When using OceanBase as storage, the list_chunk sorting is abnormal. #13198 (#13208)
Actual behavior
When using OceanBase as storage, the list_chunk sorting is abnormal. The
following is the SQL statement.
SELECT id, content_with_weight, important_kwd, question_kwd, img_id,
available_int, position_int, doc_type_kwd, create_timestamp_flt,
create_time, array_to_string(page_num_int, ',') AS page_num_int_sort,
array_to_string(top_int, ',') AS top_int_sort FROM
rag_store_284250730805059584 WHERE doc_id = '' AND kb_id IN ('') ORDER
BY page_num_int_sort ASC, top_int_sort ASC, create_timestamp_flt DESC
LIMIT 0, 20
<img width="1610" height="740" alt="image"
src="https://github.com/user-attachments/assets/84e14c30-a97f-4e8f-8c8c-6ccac915d97d"
/>
Co-authored-by: Aron.Yao <yaowei@yaoweideMacBook-Pro.local>
2026-02-25 13:36:18 +08:00
" position_int " , " create_timestamp_flt " , " page_num_int " , " top_int " ] :
2025-11-28 19:25:32 +08:00
del mom_ck [ fld ]
mothers . append ( mom_ck )
for b in range ( 0 , len ( mothers ) , settings . DOC_BULK_SIZE ) :
2026-01-20 13:29:37 +08:00
await thread_pool_exec ( settings . docStoreConn . insert , mothers [ b : b + settings . DOC_BULK_SIZE ] ,
search . index_name ( task_tenant_id ) , task_dataset_id , )
2025-11-28 19:25:32 +08:00
task_canceled = has_canceled ( task_id )
if task_canceled :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return False
2025-11-06 09:36:38 +08:00
for b in range ( 0 , len ( chunks ) , settings . DOC_BULK_SIZE ) :
2026-01-20 13:29:37 +08:00
doc_store_result = await thread_pool_exec ( settings . docStoreConn . insert , chunks [ b : b + settings . DOC_BULK_SIZE ] ,
search . index_name ( task_tenant_id ) , task_dataset_id , )
2025-10-09 12:36:19 +08:00
task_canceled = has_canceled ( task_id )
if task_canceled :
progress_callback ( - 1 , msg = " Task has been canceled. " )
2025-11-12 19:00:15 +08:00
return False
2025-10-09 12:36:19 +08:00
if b % 128 == 0 :
progress_callback ( prog = 0.8 + 0.1 * ( b + 1 ) / len ( chunks ) , msg = " " )
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 )
2025-11-06 09:36:38 +08:00
chunk_ids = [ chunk [ " id " ] for chunk in chunks [ : b + settings . DOC_BULK_SIZE ] ]
2025-10-09 12:36:19 +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. " )
2026-01-20 13:29:37 +08:00
doc_store_result = await thread_pool_exec ( settings . docStoreConn . delete , { " id " : chunk_ids } ,
2025-12-29 12:01:18 +08:00
search . index_name ( task_tenant_id ) , task_dataset_id , )
2025-12-09 19:23:14 +08:00
tasks = [ ]
for chunk_id in chunk_ids :
tasks . append ( asyncio . create_task ( delete_image ( task_dataset_id , chunk_id ) ) )
try :
await asyncio . gather ( * tasks , return_exceptions = False )
except Exception as e :
logging . error ( f " delete_image failed: { e } " )
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
raise
2025-10-09 12:36:19 +08:00
progress_callback ( - 1 , msg = f " Chunk updates failed since task { task_id } is unknown. " )
2025-11-12 19:00:15 +08:00
return False
2025-10-09 12:36:19 +08:00
return True
2025-12-29 12:01:18 +08:00
@timeout ( 60 * 60 * 3 , 1 )
2025-03-03 18:59:49 +08:00
async def do_handle_task ( task ) :
2025-10-09 12:36:19 +08:00
task_type = task . get ( " task_type " , " " )
2025-12-30 11:41:38 +08:00
if task_type == " memory " :
await handle_save_to_memory_task ( task )
return
2025-10-09 12:36:19 +08:00
if task_type == " dataflow " and task . get ( " doc_id " , " " ) == CANVAS_DEBUG_DOC_ID :
await run_dataflow ( task )
return
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 " ]
2026-02-06 14:05:32 +08:00
doc_task_llm_id = task [ " parser_config " ] . get ( " llm_id " ) or task [ " llm_id " ]
kb_task_llm_id = task [ ' kb_parser_config ' ] . get ( " llm_id " ) or task [ " llm_id " ]
task [ ' llm_id ' ] = kb_task_llm_id
2024-12-01 17:03:00 +08:00
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 ( )
2025-10-14 14:14:52 +08:00
toc_thread = None
executor = concurrent . futures . ThreadPoolExecutor ( )
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-07-15 17:19:27 +08:00
task_canceled = has_canceled ( 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
2026-03-05 17:27:17 +08:00
if task_embedding_id :
embd_model_config = get_model_config_by_type_and_name ( task_tenant_id , LLMType . EMBEDDING , task_embedding_id )
else :
embd_model_config = get_tenant_default_model_by_type ( task_tenant_id , LLMType . EMBEDDING )
embedding_model = LLMBundle ( task_tenant_id , embd_model_config , 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 )
2025-10-09 12:36:19 +08:00
if task_type [ : len ( " dataflow " ) ] == " dataflow " :
await run_dataflow ( task )
2025-09-05 18:50:46 +08:00
return
2025-10-09 12:36:19 +08:00
if task_type == " raptor " :
ok , kb = KnowledgebaseService . get_by_id ( task_dataset_id )
if not ok :
2025-12-17 10:03:33 +08:00
progress_callback ( prog = - 1.0 , msg = " Cannot found valid dataset for RAPTOR task " )
2025-10-09 12:36:19 +08:00
return
kb_parser_config = kb . parser_config
if not kb_parser_config . get ( " raptor " , { } ) . get ( " use_raptor " , False ) :
2025-10-13 11:53:48 +08:00
kb_parser_config . update (
{
" raptor " : {
" use_raptor " : True ,
" prompt " : " Please summarize the following paragraphs. Be careful with the numbers, do not make things up. Paragraphs as following: \n {cluster_content} \n The above is the content you need to summarize. " ,
" max_token " : 256 ,
" threshold " : 0.1 ,
" max_cluster " : 64 ,
" random_seed " : 0 ,
2025-11-11 16:58:47 +08:00
" scope " : " file "
2025-10-13 11:53:48 +08:00
} ,
}
)
2025-12-29 12:01:18 +08:00
if not KnowledgebaseService . update_by_id ( kb . id , { " parser_config " : kb_parser_config } ) :
2025-10-13 11:53:48 +08:00
progress_callback ( prog = - 1.0 , msg = " Internal error: Invalid RAPTOR configuration " )
return
feat: Auto-disable Raptor for structured data (Issue #11653) (#11676)
### What problem does this PR solve?
Feature: This PR implements automatic Raptor disabling for structured
data files to address issue #11653.
**Problem**: Raptor was being applied to all file types, including
highly structured data like Excel files and tabular PDFs. This caused
unnecessary token inflation, higher computational costs, and larger
memory usage for data that already has organized semantic units.
**Solution**: Automatically skip Raptor processing for:
- Excel files (.xls, .xlsx, .xlsm, .xlsb)
- CSV files (.csv, .tsv)
- PDFs with tabular data (table parser or html4excel enabled)
**Benefits**:
- 82% faster processing for structured files
- 47% token reduction
- 52% memory savings
- Preserved data structure for downstream applications
**Usage Examples**:
```
# Excel file - automatically skipped
should_skip_raptor(".xlsx") # True
# CSV file - automatically skipped
should_skip_raptor(".csv") # True
# Tabular PDF - automatically skipped
should_skip_raptor(".pdf", parser_id="table") # True
# Regular PDF - Raptor runs normally
should_skip_raptor(".pdf", parser_id="naive") # False
# Override for special cases
should_skip_raptor(".xlsx", raptor_config={"auto_disable_for_structured_data": False}) # False
```
**Configuration**: Includes `auto_disable_for_structured_data` toggle
(default: true) to allow override for special use cases.
**Testing**: 44 comprehensive tests, 100% passing
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2025-12-03 04:02:29 -05:00
# Check if Raptor should be skipped for structured data
file_type = task . get ( " type " , " " )
parser_id = task . get ( " parser_id " , " " )
raptor_config = kb_parser_config . get ( " raptor " , { } )
2025-12-09 19:23:14 +08:00
feat: Auto-disable Raptor for structured data (Issue #11653) (#11676)
### What problem does this PR solve?
Feature: This PR implements automatic Raptor disabling for structured
data files to address issue #11653.
**Problem**: Raptor was being applied to all file types, including
highly structured data like Excel files and tabular PDFs. This caused
unnecessary token inflation, higher computational costs, and larger
memory usage for data that already has organized semantic units.
**Solution**: Automatically skip Raptor processing for:
- Excel files (.xls, .xlsx, .xlsm, .xlsb)
- CSV files (.csv, .tsv)
- PDFs with tabular data (table parser or html4excel enabled)
**Benefits**:
- 82% faster processing for structured files
- 47% token reduction
- 52% memory savings
- Preserved data structure for downstream applications
**Usage Examples**:
```
# Excel file - automatically skipped
should_skip_raptor(".xlsx") # True
# CSV file - automatically skipped
should_skip_raptor(".csv") # True
# Tabular PDF - automatically skipped
should_skip_raptor(".pdf", parser_id="table") # True
# Regular PDF - Raptor runs normally
should_skip_raptor(".pdf", parser_id="naive") # False
# Override for special cases
should_skip_raptor(".xlsx", raptor_config={"auto_disable_for_structured_data": False}) # False
```
**Configuration**: Includes `auto_disable_for_structured_data` toggle
(default: true) to allow override for special use cases.
**Testing**: 44 comprehensive tests, 100% passing
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2025-12-03 04:02:29 -05:00
if should_skip_raptor ( file_type , parser_id , task_parser_config , raptor_config ) :
skip_reason = get_skip_reason ( file_type , parser_id , task_parser_config )
logging . info ( f " Skipping Raptor for document { task_document_name } : { skip_reason } " )
progress_callback ( prog = 1.0 , msg = f " Raptor skipped: { skip_reason } " )
return
2025-03-03 18:59:49 +08:00
# bind LLM for raptor
2026-03-10 14:24:33 +08:00
chat_model_config = get_model_config_by_type_and_name ( task_tenant_id , LLMType . CHAT , kb_task_llm_id )
2026-03-05 17:27:17 +08:00
chat_model = LLMBundle ( task_tenant_id , chat_model_config , lang = task_language )
2025-03-03 18:59:49 +08:00
# run RAPTOR
2025-05-27 17:41:35 +08:00
async with kg_limiter :
2025-10-09 12:36:19 +08:00
chunks , token_count = await run_raptor_for_kb (
row = task ,
kb_parser_config = kb_parser_config ,
chat_mdl = chat_model ,
embd_mdl = embedding_model ,
vector_size = vector_size ,
callback = progress_callback ,
doc_ids = task . get ( " doc_ids " , [ ] ) ,
)
2025-11-06 17:18:03 +08:00
if fake_doc_ids := task . get ( " doc_ids " , [ ] ) :
2025-12-29 12:01:18 +08:00
task_doc_id = fake_doc_ids [ 0 ] # use the first document ID to represent this task for logging purposes
2025-01-22 19:43:14 +08:00
# Either using graphrag or Standard chunking methods
2025-09-05 18:50:46 +08:00
elif task_type == " graphrag " :
2025-10-09 12:36:19 +08:00
ok , kb = KnowledgebaseService . get_by_id ( task_dataset_id )
if not ok :
2025-12-17 10:03:33 +08:00
progress_callback ( prog = - 1.0 , msg = " Cannot found valid dataset for GraphRAG task " )
2025-10-09 12:36:19 +08:00
return
kb_parser_config = kb . parser_config
if not kb_parser_config . get ( " graphrag " , { } ) . get ( " use_graphrag " , False ) :
2025-10-13 11:53:48 +08:00
kb_parser_config . update (
{
" graphrag " : {
" use_graphrag " : True ,
" entity_types " : [
" organization " ,
" person " ,
" geo " ,
" event " ,
" category " ,
] ,
" method " : " light " ,
}
}
)
2025-12-29 12:01:18 +08:00
if not KnowledgebaseService . update_by_id ( kb . id , { " parser_config " : kb_parser_config } ) :
2025-10-13 11:53:48 +08:00
progress_callback ( prog = - 1.0 , msg = " Internal error: Invalid GraphRAG configuration " )
return
2025-10-09 12:36:19 +08:00
graphrag_conf = kb_parser_config . get ( " graphrag " , { } )
2025-01-22 19:43:14 +08:00
start_ts = timer ( )
2026-03-05 17:27:17 +08:00
chat_model_config = get_model_config_by_type_and_name ( task_tenant_id , LLMType . CHAT , kb_task_llm_id )
chat_model = LLMBundle ( task_tenant_id , chat_model_config , 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 :
2025-10-09 12:36:19 +08:00
# await run_graphrag(task, task_language, with_resolution, with_community, chat_model, embedding_model, progress_callback)
result = await run_graphrag_for_kb (
row = task ,
doc_ids = task . get ( " doc_ids " , [ ] ) ,
language = task_language ,
kb_parser_config = kb_parser_config ,
chat_model = chat_model ,
embedding_model = embedding_model ,
callback = progress_callback ,
with_resolution = with_resolution ,
with_community = with_community ,
)
logging . info ( f " GraphRAG task result for task { task } : \n { result } " )
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
2025-10-09 12:36:19 +08:00
elif task_type == " mindmap " :
progress_callback ( 1 , " place holder " )
pass
return
2024-11-15 18:51:09 +08:00
else :
2024-12-01 17:03:00 +08:00
# Standard chunking methods
2026-02-06 14:05:32 +08:00
task [ ' llm_id ' ] = doc_task_llm_id
2024-12-01 17:03:00 +08:00
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 not chunks :
progress_callback ( 1. , msg = f " No chunk built from { task_document_name } " )
2024-11-15 18:51:09 +08:00
return
2024-12-01 17:03:00 +08:00
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 )
2026-02-06 14:48:24 +08:00
except TaskCanceledException :
raise
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 )
2025-10-14 14:14:52 +08:00
if task [ " parser_id " ] . lower ( ) == " naive " and task [ " parser_config " ] . get ( " toc_extraction " , False ) :
2025-12-03 12:27:50 +08:00
toc_thread = executor . submit ( build_TOC , task , chunks , progress_callback )
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 ( )
2025-07-15 17:19:45 +08:00
2026-01-19 19:35:14 +08:00
async def _maybe_insert_chunks ( _chunks ) :
2025-12-23 09:38:25 +08:00
if has_canceled ( task_id ) :
2026-02-06 14:48:24 +08:00
progress_callback ( - 1 , msg = " Task has been canceled. " )
return False
2026-01-19 19:35:14 +08:00
insert_result = await insert_chunks ( task_id , task_tenant_id , task_dataset_id , _chunks , progress_callback )
2025-12-30 11:09:18 +08:00
return bool ( insert_result )
2025-12-29 12:01:18 +08:00
2025-12-23 09:38:25 +08:00
try :
2026-01-19 19:35:14 +08:00
if not await _maybe_insert_chunks ( chunks ) :
2025-12-23 09:38:25 +08:00
return
2026-02-06 14:48:24 +08:00
if has_canceled ( task_id ) :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return
2024-11-15 18:51:09 +08:00
2025-12-23 09:38:25 +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-12-01 22:28:00 +08:00
2025-12-23 09:38:25 +08:00
DocumentService . increment_chunk_num ( task_doc_id , task_dataset_id , token_count , chunk_count , 0 )
2025-10-14 14:14:52 +08:00
2025-12-23 09:38:25 +08:00
progress_callback ( msg = " Indexing done ( {:.2f} s). " . format ( timer ( ) - start_ts ) )
2024-11-15 18:51:09 +08:00
2025-12-23 09:38:25 +08:00
if toc_thread :
d = toc_thread . result ( )
if d :
2026-01-19 19:35:14 +08:00
if not await _maybe_insert_chunks ( [ d ] ) :
2025-12-23 09:38:25 +08:00
return
DocumentService . increment_chunk_num ( task_doc_id , task_dataset_id , 0 , 1 , 0 )
if has_canceled ( task_id ) :
progress_callback ( - 1 , msg = " Task has been canceled. " )
return
task_time_cost = timer ( ) - task_start_ts
progress_callback ( prog = 1.0 , msg = " Task done ( {:.2f} s) " . format ( task_time_cost ) )
logging . info (
" Chunk doc( {} ), page( {} - {} ), chunks( {} ), token( {} ), elapsed: {:.2f} " . format (
task_document_name , task_from_page , task_to_page , len ( chunks ) , token_count , task_time_cost
)
)
finally :
if has_canceled ( task_id ) :
try :
2026-01-20 13:29:37 +08:00
exists = await thread_pool_exec (
2026-01-07 15:08:17 +08:00
settings . docStoreConn . index_exist ,
2025-12-23 09:38:25 +08:00
search . index_name ( task_tenant_id ) ,
task_dataset_id ,
)
if exists :
2026-01-20 13:29:37 +08:00
await thread_pool_exec (
2025-12-23 09:38:25 +08:00
settings . docStoreConn . delete ,
{ " doc_id " : task_doc_id } ,
search . index_name ( task_tenant_id ) ,
task_dataset_id ,
)
2025-12-30 11:09:18 +08:00
except Exception as e :
2025-12-23 09:38:25 +08:00
logging . exception (
2025-12-30 11:09:18 +08:00
f " Remove doc( { task_doc_id } ) from docStore failed when task( { task_id } ) canceled, exception: { e } " )
2024-11-15 18:51:09 +08:00
2025-11-11 17:36:48 +08:00
2025-12-29 12:01:18 +08:00
async def handle_task ( ) :
2025-03-03 18:59:49 +08:00
global DONE_TASKS , FAILED_TASKS
redis_msg , task = await collect ( )
if not task :
2025-12-09 19:23:14 +08:00
await asyncio . sleep ( 5 )
2025-03-03 18:59:49 +08:00
return
2025-10-09 12:36:19 +08:00
task_type = task [ " task_type " ]
2025-12-29 12:01:18 +08:00
pipeline_task_type = TASK_TYPE_TO_PIPELINE_TASK_TYPE . get ( task_type ,
PipelineTaskType . PARSE ) or PipelineTaskType . PARSE
2025-12-30 11:09:18 +08:00
task_id = task [ " id " ]
2025-03-03 18:59:49 +08:00
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
2025-12-30 11:09:18 +08:00
CURRENT_TASKS . pop ( task_id , None )
2025-03-03 18:59:49 +08:00
logging . info ( f " handle_task done for task { json . dumps ( task ) } " )
2026-02-06 14:48:24 +08:00
except TaskCanceledException as e :
DONE_TASKS + = 1
CURRENT_TASKS . pop ( task_id , None )
logging . info (
f " handle_task canceled for task { task_id } : { getattr ( e , ' msg ' , str ( e ) ) } "
)
2025-03-03 18:59:49 +08:00
except Exception as e :
FAILED_TASKS + = 1
2025-12-30 11:09:18 +08:00
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 )
2025-12-30 11:09:18 +08:00
set_progress ( task_id , prog = - 1 , msg = f " [Exception]: { err_msg } " )
except Exception as e :
logging . exception ( f " [Exception]: { str ( e ) } " )
2025-03-03 18:59:49 +08:00
pass
logging . exception ( f " handle_task got exception for task { json . dumps ( task ) } " )
2025-10-09 12:36:19 +08:00
finally :
task_document_ids = [ ]
if task_type in [ " graphrag " , " raptor " , " mindmap " ] :
task_document_ids = task [ " doc_ids " ]
if not task . get ( " dataflow_id " , " " ) :
2025-12-29 12:01:18 +08:00
PipelineOperationLogService . record_pipeline_operation ( document_id = task [ " doc_id " ] , pipeline_id = " " ,
task_type = pipeline_task_type ,
fake_document_ids = task_document_ids )
2025-10-09 12:36:19 +08:00
2025-03-03 18:59:49 +08:00
redis_msg . ack ( )
2025-11-10 12:51:39 +08:00
async def get_server_ip ( ) - > str :
# get ip by udp
try :
with socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) as s :
s . connect ( ( " 8.8.8.8 " , 80 ) )
return s . getsockname ( ) [ 0 ]
except Exception as e :
logging . error ( str ( e ) )
return ' Unknown '
2025-03-03 18:59:49 +08:00
async def report_status ( ) :
2026-01-04 11:24:05 +08:00
"""
Periodically reports the executor ' s heartbeat
"""
global PENDING_TASKS , LAG_TASKS , DONE_TASKS , FAILED_TASKS
ip_address = await get_server_ip ( )
pid = os . getpid ( )
# Register the executor in Redis
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 )
2026-01-04 11:24:05 +08:00
2024-08-21 17:48:00 +08:00
while True :
2026-01-04 11:24:05 +08:00
now = datetime . now ( )
now_ts = now . timestamp ( )
group_info = REDIS_CONN . queue_info ( settings . get_svr_queue_name ( 0 ) , SVR_CONSUMER_GROUP_NAME ) or { }
PENDING_TASKS = int ( group_info . get ( " pending " , 0 ) )
LAG_TASKS = int ( group_info . get ( " lag " , 0 ) )
current = copy . deepcopy ( CURRENT_TASKS )
heartbeat = json . dumps ( {
" ip_address " : ip_address ,
" pid " : pid ,
" 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 ,
} )
# Report heartbeat to Redis
2024-08-21 17:48:00 +08:00
try :
2026-01-04 11:24:05 +08:00
REDIS_CONN . zadd ( CONSUMER_NAME , heartbeat , now_ts )
except Exception as e :
logging . warning ( f " Failed to report heartbeat: { e } " )
else :
2024-11-15 14:43:55 +08:00
logging . info ( f " { CONSUMER_NAME } reported heartbeat: { heartbeat } " )
2026-01-04 11:24:05 +08:00
# Clean up own expired heartbeat
try :
REDIS_CONN . zremrangebyscore ( CONSUMER_NAME , 0 , now_ts - 60 * 30 )
except Exception as e :
logging . warning ( f " Failed to clean heartbeat: { e } " )
2025-04-19 16:18:51 +08:00
2026-01-04 11:24:05 +08:00
# Clean other executors
lock_acquired = False
try :
lock_acquired = redis_lock . acquire ( )
2025-12-30 11:09:18 +08:00
except Exception as e :
2026-01-04 11:24:05 +08:00
logging . warning ( f " Failed to acquire Redis lock: { e } " )
if lock_acquired :
try :
task_executors = REDIS_CONN . smembers ( " TASKEXE " ) or set ( )
for worker_name in task_executors :
if worker_name == CONSUMER_NAME :
continue
try :
last_heartbeat = REDIS_CONN . REDIS . zrevrange ( worker_name , 0 , 0 , withscores = True )
except Exception as e :
logging . warning ( f " Failed to read zset for { worker_name } : { e } " )
continue
if not last_heartbeat or now_ts - last_heartbeat [ 0 ] [ 1 ] > WORKER_HEARTBEAT_TIMEOUT :
logging . info ( f " { worker_name } expired, removed " )
REDIS_CONN . srem ( " TASKEXE " , worker_name )
REDIS_CONN . delete ( worker_name )
except Exception as e :
logging . warning ( f " Failed to clean other executors: { e } " )
finally :
redis_lock . release ( )
2025-12-09 19:23:14 +08:00
await asyncio . sleep ( 30 )
2025-07-15 17:19:45 +08:00
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 ( ) :
task executor issues (#12006)
### What problem does this PR solve?
**Fixes #8706** - `InfinityException: TOO_MANY_CONNECTIONS` when running
multiple task executor workers
### Problem Description
When running RAGFlow with 8-16 task executor workers, most workers fail
to start properly. Checking logs revealed that workers were
stuck/hanging during Infinity connection initialization - only 1-2
workers would successfully register in Redis while the rest remained
blocked.
### Root Cause
The Infinity SDK `ConnectionPool` pre-allocates all connections in
`__init__`. With the default `max_size=32` and multiple workers (e.g.,
16), this creates 16×32=512 connections immediately on startup,
exceeding Infinity's default 128 connection limit. Workers hang while
waiting for connections that can never be established.
### Changes
1. **Prevent Infinity connection storm** (`rag/utils/infinity_conn.py`,
`rag/svr/task_executor.py`)
- Reduced ConnectionPool `max_size` from 32 to 4 (sufficient since
operations are synchronous)
- Added staggered startup delay (2s per worker) to spread connection
initialization
2. **Handle None children_delimiter** (`rag/app/naive.py`)
- Use `or ""` to handle explicitly set None values from parser config
3. **MinerU parser robustness** (`deepdoc/parser/mineru_parser.py`)
- Use `.get()` for optional output fields that may be missing
- Fix DISCARDED block handling: change `pass` to `continue` to skip
discarded blocks entirely
### Why `max_size=4` is sufficient
| Workers | Pool Size | Total Connections | Infinity Limit |
|---------|-----------|-------------------|----------------|
| 16 | 32 | 512 | 128 ❌ |
| 16 | 4 | 64 | 128 ✅ |
| 32 | 4 | 128 | 128 ✅ |
- All RAGFlow operations are synchronous: `get_conn()` → operation →
`release_conn()`
- No parallel `docStoreConn` operations in the codebase
- Maximum 1-2 concurrent connections needed per worker; 4 provides
safety margin
### MinerU DISCARDED block bug
When MinerU returns blocks with `type: "discarded"` (headers, footers,
watermarks, page numbers, artifacts), the previous code used `pass`
which left the `section` variable undefined, causing:
- **UnboundLocalError** if DISCARDED is the first block
- **Duplicate content** if DISCARDED follows another block (stale value
from previous iteration)
**Root cause confirmed via MinerU source code:**
From
[`mineru/utils/enum_class.py`](https://github.com/opendatalab/MinerU/blob/main/mineru/utils/enum_class.py#L14):
```python
class BlockType:
DISCARDED = 'discarded'
# VLM 2.5+ also has: HEADER, FOOTER, PAGE_NUMBER, ASIDE_TEXT, PAGE_FOOTNOTE
```
Per [MinerU
documentation](https://opendatalab.github.io/MinerU/reference/output_files/),
discarded blocks contain content that should be filtered out for clean
text extraction.
**Fix:** Changed `pass` to `continue` to skip discarded blocks entirely.
### Testing
- Verified all 16 workers now register successfully in Redis
- All workers heartbeating correctly
- Document parsing works as expected
- MinerU parsing with DISCARDED blocks no longer crashes
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
---------
Co-authored-by: user210 <user210@rt>
2025-12-18 04:03:30 +02:00
# Stagger executor startup to prevent connection storm to Infinity
# Extract worker number from CONSUMER_NAME (e.g., "task_executor_abc123_5" -> 5)
try :
worker_num = int ( CONSUMER_NAME . rsplit ( " _ " , 1 ) [ - 1 ] )
# Add random delay: base delay + worker_num * 2.0s + random jitter
# This spreads out connection attempts over several seconds
startup_delay = worker_num * 2.0 + random . uniform ( 0 , 0.5 )
if startup_delay > 0 :
logging . info ( f " Staggering startup by { startup_delay : .2f } s to prevent connection storm " )
await asyncio . sleep ( startup_delay )
except ( ValueError , IndexError ) :
pass # Non-standard consumer name, skip delay
2024-11-30 18:48:06 +08:00
logging . info ( r """
2025-10-22 09:29:20 +08:00
____ __ _
2025-10-21 09:38:20 +08:00
/ _ / ___ ____ ____ _____ / / _ ( _ ) ___ ____ ________ ______ _____ _____
/ / / __ \/ __ ` / _ \/ ___ / __ / / __ \/ __ \ / ___ / _ \/ ___ / | / / _ \/ ___ /
2025-10-22 09:29:20 +08:00
_ / / / / / / / _ / / __ ( __ ) / _ / / / _ / / / / / ( __ ) __ / / | | / / __ / /
/ ___ / _ / / _ / \__ , / \___ / ____ / \__ / _ / \____ / _ / / _ / / ____ / \___ / _ / | ___ / \___ / _ /
/ ____ /
2024-11-30 18:48:06 +08:00
""" )
2025-10-21 09:38:20 +08:00
logging . info ( f ' RAGFlow version: { get_ragflow_version ( ) } ' )
2025-10-23 23:02:27 +08:00
show_configs ( )
2024-11-15 22:55:41 +08:00
settings . init_settings ( )
2025-11-06 09:36:38 +08:00
settings . check_and_install_torch ( )
2025-12-03 15:15:00 +08:00
logging . info ( f ' default embedding config: { settings . EMBEDDING_CFG } ' )
2025-11-06 09:36:38 +08:00
settings . 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 )
2025-12-09 19:23:14 +08:00
report_task = asyncio . create_task ( report_status ( ) )
tasks = [ ]
2026-01-12 12:48:23 +08:00
logging . info ( f " RAGFlow ingestion is ready after { time . time ( ) - start_ts } s initialization. " )
2025-12-09 19:23:14 +08:00
try :
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-12-09 19:23:14 +08:00
t = asyncio . create_task ( task_manager ( ) )
tasks . append ( t )
finally :
for t in tasks :
t . cancel ( )
await asyncio . gather ( * tasks , return_exceptions = True )
report_task . cancel ( )
await asyncio . gather ( report_task , return_exceptions = True )
2025-03-03 18:59:49 +08:00
logging . error ( " BUG!!! You should not reach here!!! " )
2024-11-30 18:48:06 +08:00
2025-12-29 12:01:18 +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-12-09 19:23:14 +08:00
asyncio . run ( main ( ) )