Repository navigation
Feat/go stop parse documents - #3
Closed
xugangqiang wants to merge 22 commits into
Closed
xugangqiang wants to merge 22 commits into
xugangqiang wants to merge 22 commits into
Conversation
…w#15565) ### What problem does this PR solve? agent template smart_customer_service_specialist.json ### Type of change - [x] Refactoring
### What problem does this PR solve? remove old and add latest cohere models ### Type of change - [x] Refactoring - [x] Other (please describe): update models
…e. (infiniflow#15401) ### What problem does this PR solve? Fix: Switching pagesize on a chunk page did not reset the current page. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
Fix: no more @token_required
### What problem does this PR solve? 1. Add license announcement 2. Add sanity check on API config 3. Add base class: BaseModel 4. Add GetBaseURL ### Type of change - [x] Refactoring --------- Signed-off-by: Jin Hai <[email protected]>
…hensive test suite (infiniflow#15471) ## Summary Decomposes the monolithic `task_executor.py` (1945 lines) into a 6-layer architecture with clear separation of concerns. The refactored code is functionally equivalent to the original, verified through 400 passing tests and a production-vs-dry-run comparison framework. ## Architecture ``` entry (task_manager) └─ orchestration (task_handler) ├─ services (chunk_service, embedding_service, dataflow_service, raptor_service, post_processor) │ └─ utilities (chunk_builder, chunk_post_processor, embedding_utils) └─ infrastructure (task_context, recording_context, interceptor) ``` Key design decisions: - **TaskContext** — typed facade over raw task dict, injects rate limiters + callbacks via composition - **RecordingContext + Comparator** — enables side-by-side production vs dry-run execution for safe migration - **NullRecordingContext** — zero-allocation no-op for production, uses `__slots__` - **WriteOperationInterceptor** — FIFO replay of previous runs function returns for comparison mode ## Migration Strategy The original `handle_task()` in `task_executor.py` uses a 3-way switch via `TE_RUN_MODE`: - `TE_RUN_MODE=0` (default) → runs refactored code - `TE_RUN_MODE=1` → runs both original + refactored, compares all intermediate results - `TE_RUN_MODE=2` → runs original code (fallback) The comparison mode (`TE_RUN_MODE=1`) records ~40 intermediate values (chunks, vectors, token counts, func return values) from the production run and replays them during dry-run, then uses `ContextComparator` to report mismatches. ## Functional Equivalence Fixes All divergences between original and refactored code were identified and fixed: - Timeout decorators (handle/build_chunks/raptor/embedding) - NullRecordingContext leak in finally block causing RuntimeError - MinIO None-binary check with proper FileNotFoundError - Dataflow dispatch after embedding binding + init_kb - Memory task missing return after processing - RAPTOR checkpoint progress reporting - Tag cache (get_tags_from_cache/set_tags_to_cache) restoration - dataflow_id correction in _load_dsl - Language default Chinese, dead code guard removal - embed_chunks made async with proper thread_pool_exec - Full GraphRAG default configuration (10 parameters) - Hardcoded q_768_vec fallback removal in RAPTOR ## Test Changes - 20 new tests covering table parser manual mode, tag cache, embedding edge cases, RAPTOR checkpoint, dataflow_id correction, storage binary None, cancel cleanup, metadata=None boundary - Unified `make_task_context`/`make_task_dict` factories eliminated 10+ duplicated helpers - DataflowService tests migrated from internal method mocks to IO boundary mocks (real orchestration code executes) - Parametrized duplicate build_chunks post-processor tests - 7 raptor tests modernized to @pytest.mark.asyncio - Mock count per test reduced through boundary-level mocking strategy **Test count: 400 passing, 0 warnings, 0 skips** ## Files Changed | File | Change | |------|--------| | `rag/svr/task_executor.py` | +1 line (NullRecordingContext fix) | | `rag/svr/task_executor_refactor/task_handler.py` | Orchestration layer, 8 logic fixes | | `rag/svr/task_executor_refactor/chunk_service.py` | +timeout + None-check | | `rag/svr/task_executor_refactor/embedding_service.py` | sync→async rewrite | | `rag/svr/task_executor_refactor/dataflow_service.py` | dataflow_id fix + timeout | | `rag/svr/task_executor_refactor/raptor_service.py` | checkpoint fix + assert | | `rag/svr/task_executor_refactor/chunk_post_processor.py` | tag cache restore | | `rag/svr/task_executor_refactor/task_context.py` | language default fix | | `test/.../conftest.py` | +294 lines shared helpers | | `test/.../*.py` | 15 test files refactored, 20 new tests | --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
### What problem does this PR solve? Remove unused code. ### Type of change - [x] Refactoring Signed-off-by: Jin Hai <[email protected]>
…niflow#15536) ## Summary Fixes infiniflow#15534 — `update_document_name_only()` crashes with `AttributeError` when `File2Document` exists but the linked `File` row was deleted. `update_document_name_only()` in `document_api_service.py` called `FileService.get_by_id()` when a `File2Document` row existed, then accessed `file.id` without checking the lookup result. An orphan `File2Document` link (file deleted, mapping left behind) caused document rename via `PATCH /api/v1/datasets/{dataset_id}/documents/{document_id}` to return HTTP 500. This PR mirrors guards used in `file2document_api.py` and `file_api_service.py`: skip the optional file rename when the file is missing, and still update the document record and search index. ## Changes - `api/apps/services/document_api_service.py` — check `e and file` before `FileService.update_by_id` - `test/unit_test/api/apps/services/test_update_document_name_only.py` — regression tests (orphan link + happy path) ## Test plan - [x] `pytest test/unit_test/api/apps/services/test_update_document_name_only.py -v` - [ ] Manual: PATCH document `name` when `File2Document` points to a non-existent `file_id` → 200, document/index renamed, no 500
…w#15431) ### What problem does this PR solve? Adds a shared safe default implementation for unsupported Go model-driver capability methods and migrates the confirmed panic-stub providers to use it. The Go `ModelDriver` interface requires providers to implement many capability methods even when the provider does not support them. XunFei had unsupported capability methods implemented as `panic("implement me")`, Mistral still had a panic in `ParseFile`, and HuaweiCloud carried an unreachable `panic("implement me")` after a normal chat return. ### Type of change - [x] Refactoring Co-authored-by: Haruko386 <[email protected]>
Fix: consolidate beta auth
### What problem does this PR solve? The following API is available in go > /api/v1/connectors/google/oauth/web/start POST > /api/v1/connectors/gmail/oauth/web/callback GET > /api/v1/connectors/google-drive/oauth/web/callback GET > /api/v1/connectors/google/oauth/web/result POST ### Type of change - [x] New Feature (non-breaking change which adds functionality)
…finiflow#15577) ## Summary Migrate the batch document deletion endpoint from Python to Go. Two modes supported: explicit `ids` list and `delete_all`. ## Changes | File | Change | |------|--------| | `internal/dao/file2document.go` | Add `GetByDocumentID`, `DeleteByDocumentID` | | `internal/dao/file2document_test.go` | 5 new tests | | `internal/dao/kb_test.go` | 2 new tests (`DecreaseDocumentNum`) | | `internal/service/document.go` | Add `deleteDocumentFull` + `DeleteDocuments`, refactor `DeleteDocument` | | `internal/service/document_test.go` | 10 new tests | | `internal/handler/document.go` | Add `documentServiceIface` + `DeleteDocuments` handler | | `internal/handler/document_test.go` | 7 new tests | | `internal/router/router.go` | Register `DELETE /:dataset_id/documents` | | `cmd/server_main.go` | Support `RAGFLOW_DICT_PATH` env var | | `internal/binding/rag_analyzer.go` | Use `-lpcre2-8` dynamic linking | | `internal/dao/database.go` | Skip Error 1091/1138 during migration | | `internal/service/llm.go` | Fix vet warning | ## Per-document cleanup - Delete tasks from DB - Hard-delete document + decrement KB counters - Delete chunks from document engine (nil-guarded) - Delete metadata from document engine (nil-guarded) - Remove file2document mapping + file record + storage blob ## Test Results **24 unit tests all passing** (7 DAO + 10 service + 7 handler) using SQLite :memory: + gin.TestMode. See [test report](docs/test_report_delete_documents.md) for manual integration test results. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Migrate the batch document deletion endpoint from Python to Go. Two modes supported: explicit ids list, and delete_all. Changes: - dao/file2document: add GetByDocumentID, DeleteByDocumentID - dao/kb: add DecrementCounters (already existed) with tests - service/document: add deleteDocumentFull (per-doc cleanup) + DeleteDocuments (batch orchestration) - handler/document: add DeleteDocuments handler with request validation - router: register DELETE /:dataset_id/documents route - cmd/server_main: support RAGFLOW_DICT_PATH env var for tokenizer dict path - binding/rag_analyzer: use -lpcre2-8 dynamic linking (fixes host dev) - dao/database: skip Error 1091/1138 during migration (coexist with Python schema) - service/llm: fix non-constant format string vet warning Per-document cleanup includes: - Task deletion from DB - Document hard-delete + KB counter decrement - Chunk deletion from document engine (nil-guarded) - Metadata deletion from document engine (nil-guarded) - File2document mapping + file record + storage blob removal Unit tests: 24 passing (7 DAO + 10 service + 7 handler) Tested with SQLite :memory: + gin.TestMode, no external deps. Co-Authored-By: Claude Opus 4.8 <[email protected]>
A single file_id can be shared across multiple documents via file2document rows with different document_id. Before deleting the file record and its storage blob, check whether any other document still references the same file_id. Only delete file/blob when no other references remain. Add TestDeleteDocumentFull_SharedFilePreserved to verify shared file survives when one referencing document is deleted.
-lpcre2-8 linker flag finds either .a or .so automatically. Update the build-time library checks to match.
- Add GetByDocID to TaskDAO for querying tasks by document ID - Add StopParseDocuments to DocumentService with Redis cancel signal support - Add StopParseDocuments handler with request validation and access check - Add POST /:dataset_id/documents/stop route - Add unit tests: 3 DAO + 8 service + 5 handler tests Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extract five sub-methods from deleteDocumentFull: - resolveDocAndKB — load document + knowledgebase - deleteDocTasks — delete task rows - deleteDocEngineData — delete chunks + metadata from engine - deleteDocRecordWithCounters — hard-delete doc + decrement KB - cleanupFileReferences — delete f2d + file + blob (shared-safe) deleteDocumentFull is now a thin orchestrator. Add 10 targeted unit tests for the sub-methods.
validateDocsInDataset is shared between DeleteDocuments and StopParseDocuments, removing duplicate validation logic. cancelDocParse encapsulates per-document parse cancellation: Redis cancel signal + run status update. StopParseDocuments is now a thin orchestrator, same pattern as deleteDocumentFull.
…hCounters DocumentDAO.Delete now returns (int64, error). deleteDocRecordWithCounters wraps the delete + counter decrement in a transaction and only decrements KB counters when RowsAffected > 0, preventing permanent dataset stat skew on retries or concurrent deletes.
…ferences If DeleteByIDs returns an error the file row is still live; removing the blob anyway would leave a dangling file record. Bail out to keep the blob intact so the record remains usable on retry.
Single-line wrapper with no extra logic beyond the DAO call + log. Task deletion is already covered by TestDeleteDocumentFull_Basic.
xugangqiang
force-pushed
the
feat/go-stop-parse-documents
branch
from
June 3, 2026 13:22
7197fc8 to
db59e98
Compare
xugangqiang
added a commit
that referenced
this pull request
Jul 27, 2026
- token.go Update: guard overlapped_percent behind key presence so a partial config update preserves the previously configured value instead of resetting it to 0 (finding #3). - schema clampOverlappedPercent: clamp to [0,90] BEFORE the float->int truncation so huge inputs (e.g. 1e300, math.MaxFloat64) normalize to 90, matching Python's normalize_overlapped_percent, instead of 0 (finding #4). - Tests: add overflow cases to TestNormalizeOverlappedPercent and a new TestTokenChunkerParam_UpdatePreservesOverlappedPercent regression test. Refs infiniflow#17396
xugangqiang
added a commit
that referenced
this pull request
Jul 28, 2026
- Scope temperature to 0.2 only for keyword/question extraction; the generic field-extraction path now leaves Temperature unset to use the model default, matching Python's generic Extractor (generator.py). - Merge runAutoKeywords/runAutoQuestions with their *Locked duplicates into single functions taking a *sync.Mutex (nil = sequential); map access stays race-safe under concurrency. - retryInvoker.Invoke now returns a nil response on failure instead of the last partial response. - RetryWithBackoff gains an optional shouldRetry predicate; the extractor chat call uses a lightweight classifier so non-transient errors (auth/4xx/config) stop retrying immediately. The greedy </think> strip already matched Python's re.sub behavior, so no change there. Addresses review items #3, #5, #6, #7 on PR infiniflow#17470.
xugangqiang
added a commit
that referenced
this pull request
Aug 17, 2026
Rewrite the RED/legacy header comments so they describe the now-implemented (parity) behavior instead of the old pre-fix behavior: - DuplicateFigureRegions: Go now fuses the overlapping pair (no synthetic dup) - SyntheticFigureEquation: per-type synthetic counters (figure/equation separate) - TieBreakRegionCoverage: mirrors (ov,_ov) tuple, higher _ov wins Also reword the #3 t.Errorf to a neutral failure description. No logic change; parity tests stay GREEN.
xugangqiang
added a commit
that referenced
this pull request
Aug 17, 2026
The Go DLA client (inference.Client.DLA) kept footer/header/reference regions whose detection confidence was below 0.4. Python's production path (parse_into_bboxes -> LayoutRecognizer.__call__, deepdoc/vision/layout_recognizer.py:97 and :379) drops such regions via a 0.4 garbage gate over garbage_layouts=['footer','header','reference']. The shared /predict/dla backend runs LayoutRecognizer.forward, which does NOT apply that gate, so the Go client was the only place the filter was missing. Add the same 0.4 garbage gate in Client.DLA so low-confidence footer/ header/reference regions are dropped, matching Python's extracted layout typing, section cropping, and figure/table detection. Add TestDeepDocHTTP_DLA_DropsLowConfidenceGarbageLayout: an in-memory httptest /predict/dla backend returns a low-confidence 'reference' region (next to a high-confidence 'text' region); the test asserts only the high-confidence region survives. It failed before the gate and passes now. Parity audit item #3.
xugangqiang
added a commit
that referenced
this pull request
Sep 8, 2026
Addresses the architecture review (F1-F3) and CodeRabbit findings on the
per-chunk cache introduced in feat/ingestion-checkpoint-chunk-cache.
Cache key contract (F1/F2):
- chunkcache.Key now guards an empty modelID symmetrically with an empty
chunkID, so a caller that forgot to resolve the model cannot collapse
every model onto one bucket. The doc spells out the modelID semantics:
embd_id for the "emb" kind, and the chat model id (or resolved tenant
default) for extractor:*/meta/tagger kinds.
- extractor.go adds extractorCacheModelID, which resolves an empty llmID to
the real tenant-default chat model identity ("driver/modelName") instead
of keying on the empty override. This keeps the default-model path cached
while still scoping entries per actual model.
Key coverage of model inputs (F3 / CodeRabbit #2):
- tagger key now folds in the chunk text from getChunkText (includes
important_kwd), so a keyword change busts stale tags.
- embedding key now includes the truncated embedded text (post field
selection + truncation), so a Fields/model change forces a fresh embed.
- Added regression tests pinning the model dimension into the key for the
extractor / meta / tagger kinds (TestKey_EmptyModelIDYieldsNoKey,
TestEmbedChunks_CacheKeyScopedByFields,
TestTaggerCacheKey_ScopedByChunkID_ModelAndText).
Manifest TTL rollback (CodeRabbit #1):
- chunkcache.Set now deletes the manifest key if Expire fails, instead of
leaving a TTL-less set that leaks one key per abandoned task.
Purge ordering (CodeRabbit #3):
- Moved chunkcache.PurgeTask to after all failure-capable persist steps
(index write, compiled-product reconcile, Wiki active-state) succeed, so a
retry still finds the cache intact and does not re-pay every
embedding/LLM call — which is the cost the cache exists to absorb.
All three packages (chunkcache, component, task) pass `build.sh --test`.
xugangqiang
added a commit
that referenced
this pull request
Sep 9, 2026
… keys Review finding #3: on the default-model path (empty llm_id) the model identity used to key the per-chunk cache was re-resolved inside every cache-key build (callTextCached / runEnableMetadata / llmTagChunk), so a run over N chunks paid N extra resolveExtractorChatTarget calls — and, with no cache, N wasted resolutions per chunk. The default model is the most common path, so this is a real regression introduced by the correctness fix that started keying on the resolved model. Resolve the cache-key model identity once in Invoke and thread it through extractorInputs / llmTagChunk, reusing it across all chunks. Direct test construction of extractorInputs keeps working via a per-call fallback when modelID is empty. Add TestExtractor_ResolvesDefaultModelOncePerRun to lock the invariant (resolverCalls == stub.Calls()+1: one run-level resolution, reused across chunks) — it fails at 20 calls before this change and passes at 11 for a 5-chunk keywords+metadata run. Co-Authored-By: CodeBuddy <[email protected]>
xugangqiang
added a commit
that referenced
this pull request
Nov 4, 2026
- Remove the never-used err field from extractorResolvedTarget: only successful resolutions are cached, so the stored entry is always nil and cache hits now return nil explicitly. - Strip "review finding E1 / #3" and "RED before implementation" references from code and test comments; they described the PR review process, not the runtime contract. - Move substantive resolution docs onto the *_Uncached implementations and keep the cache-aware wrappers documented at their own declaration. Verified non-behavioral: unit (build.sh --test) and integration (build.sh --test-integration-go) for ./internal/ingestion/component/... pass. Co-authored-by: CodeBuddy <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What problem does this PR solve?
Briefly describe what this PR aims to solve. Include background context that will help reviewers understand the purpose of the PR.
Type of change