Skip to content

fix: avoid tiktoken network download on offline startup (#15943) - #16063

Closed
RykerFeng wants to merge 438 commits into
infiniflow:mainfrom
RykerFeng:fix/tiktoken-offline-cache-15943
Closed

RykerFeng wants to merge 438 commits into
infiniflow:mainfrom
RykerFeng:fix/tiktoken-offline-cache-15943

Conversation

@RykerFeng

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #15943.

In air-gapped / offline deployments RAGFlow crashes at startup with:

Failed to resolve 'openaipublic.blob.core.windows.net' ([Errno -2] Name or service not known)

This is tiktoken trying to download the cl100k_base encoding over the network.

The image already ships that encoding cache at /ragflow/9b5ad71b2ce5302211f9c61530b329a4922fc6a4 (see Dockerfile), and tiktoken will use it only when TIKTOKEN_CACHE_DIR points at /ragflow. Previously that env var was set only as an import side-effect of common/token_utils.py. Any code path that touched tiktoken before that import (e.g. rag/app/resume.py calls tiktoken.encoding_for_model(...) at module load) bypassed the cache and fell back to the network download, which fails offline.

How does it work?

  • Dockerfile: set ENV TIKTOKEN_CACHE_DIR=/ragflow so the bundled cache is used by every process from container start, independent of Python import order.
  • common/token_utils.py: use os.environ.setdefault(...) instead of unconditional assignment, so an operator-provided TIKTOKEN_CACHE_DIR is preserved.
  • rag/app/resume.py: widen the optional-tiktoken guard from except ImportError to except Exception, so a missing cache + no network degrades gracefully (heuristic path) instead of breaking module import.
  • Add regression tests for the cache-dir configuration in test/unit_test/common/test_token_utils.py.

Verification

Reproduced and verified the fix in a fully network-isolated container (docker run --network none):

Unit tests: pytest test/unit_test/common/test_token_utils.py → 44 passed. ruff check clean.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

Lynn-Inf and others added 30 commits June 3, 2026 14:43
…out llms in json (infiniflow#15550)

### What problem does this PR solve?

As title.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
…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)
### 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]>
### 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]>
…infiniflow#15511)

### What problem does this PR solve?

### Problem

On the Model Providers page, the Embedding Model dropdown in System
Model Settings shows empty (no default selected), even though a default
embedding model is configured in `service_conf.yaml`.

### Root Cause

Two issues were identified:

1. **Backend: `_get_model_info` fails for unregistered providers**
The tenant's `embd_id` is set to `bge-m3@xxxx` during initialization
(from the placeholder config `factory: 'xxxx'`). The `_get_model_info`
function requires the provider to exist in `tenant_model_provider`
table, but `xxxx` is never a real provider. Even after the user adds a
real provider (e.g., ZHIPU-AI), the stale `embd_id` still references the
non-existent one, causing the function to return `None`.

2. **Frontend: default models cache not invalidated after adding
provider**
`useAddProviderInstance` only invalidates `addedProviders` and
`allModels` caches after adding a provider instance, but does **not**
invalidate the `defaultModels` cache. This means the default model list
is not re-fetched until the user manually refreshes the page.

### Fix

**`api/apps/services/models_api_service.py`**

- Added `_resolve_model_from_tenant_providers()` helper: when the
default model's provider doesn't exist (e.g., placeholder `xxxx`), it
searches through the tenant's actually registered providers for a model
of the same type and returns the first match.
- When an instance name doesn't match (e.g., `"default"` vs actual name
`"1"`), the function now auto-resolves to the first real instance under
that provider.
- Falls back to `FACTORY_LLM_INFOS` validation when neither provider nor
instance exists.

**`web/src/hooks/use-llm-request.tsx`**

- Added `queryClient.invalidateQueries({ queryKey:
LlmKeys.defaultModels() })` to `useAddProviderInstance` so that the
default model list is re-fetched immediately after a provider instance
is added, eliminating the need for a manual page refresh.

### Testing

- Verified with a tenant whose `embd_id=bge-m3@xxxx` and only provider
is ZHIPU-AI (instance `1`): `_resolve_model_from_tenant_providers`
correctly resolves to `embedding-2@1@ZHIPU-AI`.
- After adding a provider via the UI, the embedding model dropdown now
immediately shows the resolved default without requiring a page refresh.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

---------

Signed-off-by: noob <[email protected]>
…iflow#15508)

## Summary
Restore the `DocumentService.accessible(doc_id, current_user.id)` check
that PR infiniflow#15146 dropped from the REST document preview handler. Any
authenticated caller could download any tenant's document bytes by
guessing/knowing the `doc_id`.

## Root cause
`api/apps/restful_apis/document_api.py` — the `GET
/documents/<doc_id>/preview` handler called `DocumentService.get_by_id`
and went straight to `File2DocumentService.get_storage_address` +
`STORAGE_IMPL.get`, with no tenant check between the lookup and the
read. The handler's docstring even promises "user must belong to the
tenant that owns the document's knowledge base" — the code didn't
enforce it.

## Fix
- Add `current_user` to the existing `api.apps` import.
- Immediately after `get_by_id`, call
`DocumentService.accessible(doc_id, current_user.id)`; on denial, return
the **same** `get_data_error_result(message="Document not found!")`
shape used for the missing-doc branch. That makes a cross-tenant probe
indistinguishable from a missing-doc probe, preventing ID enumeration
(the issue body calls this out explicitly).
- Emit `logging.warning` with caller user + doc_id for audit.
- Restores symmetry with peer routes that already call
`accessible(doc_id, user_id)` (e.g. `_run_sync` at
`document_api.py:1380`).

## Test plan
Adds
`test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py`:

- **`test_cross_tenant_preview_is_denied`** — owner tenant ≠ caller
tenant; asserts the response shape is `Document not found!` and the
storage backend (`thread_pool_exec(STORAGE_IMPL.get, ...)`) is **never**
invoked.
- **`test_missing_doc_returns_not_found`** — missing-doc behaviour
unchanged.

Stub-loader pattern mirrors
`test/unit_test/api/apps/sdk/test_dify_retrieval.py` (added in infiniflow#15028,
passing in CI).

## Provenance — how this fix was produced

This PR was authored against a small cited knowledge base committed in
the working tree as a `.vouch/` (see
[vouchdev/vouch](https://github.com/vouchdev/vouch)). The loop used
here:

1. **Grounding first.** Before reading the handler, queried the KB for
prior context: `vouch context "tenant scoped accessible authorization"`
→ retrieved a cited claim distilled from PR infiniflow#15028 (which restored the
same `accessible()` check on `/dify/retrieval`). The retrieved rule:

> *ragflow REST endpoints that load by tenant-scoped id must call
`<Service>.accessible(id, tenant_id)` after `get_by_id` and before
storage/DB read; deny with code 109 'No authorization.' and log a
warning. Established by PR infiniflow#15028.*

2. **Applied the pattern with a domain refinement.** For an API/JSON
endpoint, `No authorization.` is the right denial shape. For a
**byte-streaming, browser-facing** endpoint like `/preview`, leaking
*existence* itself enables enumeration — so per the issue's expected
behaviour, this PR denies with `Document not found!` (indistinguishable
from missing) instead. Same auth check, narrower response.

3. **Recorded the refinement back into the KB** as a new cited claim, so
the next IDOR-class issue starts already grounded in both the general
pattern and the byte-route nuance.

Net effect of the workflow: the fix replicates a known-good pattern
instead of reinventing it, *and* the place where the pattern was nuanced
is now retrievable for the next pass. Mechanism is fully independent of
this PR — it's not a runtime dependency, just process discipline.

Closes infiniflow#15501
)

Restore `DocumentService.accessible` on `GET
/api/v1/documents/{doc_id}/preview` so cross-tenant users cannot stream
documents by UUID.

Fixes infiniflow#15501

### What problem does this PR solve?

PR infiniflow#15146 (`71a52d579`) moved the agent attachment download route and
accidentally removed the `DocumentService.accessible(doc_id,
current_user.id)` guard from the REST preview handler. The endpoint
still requires login, but any authenticated user who knows another
tenant's `doc_id` can download the raw file bytes.

This restores the same authorization check that existed before infiniflow#15146,
returning a generic `"Document not found!"` when access is denied (no
cross-tenant ID enumeration). SDK download routes tracked in infiniflow#15125 are
unchanged.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

think stream tail handling
### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

Fix:
- Verify provider with empty llm list in llm_factories.json
- Set search bot's chat_llm_name, use tenant default chat model as
default

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

remove duplicate document preview access check

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

Markdown extraction currently applies custom delimiters before
respecting fenced code blocks. When a delimiter such as a newline is
configured, fenced code can be split into separate chunks, and longer
outer fences can be closed incorrectly by shorter nested fences.

This PR keeps the fix intentionally narrow for the Markdown chunking
discussion in infiniflow#15482:

- preserve fenced code blocks when delimiter-based extraction is used
- support both backtick and tilde fences
- respect fence length so longer outer fences can contain shorter inner
fences
- keep delimiter splitting unchanged outside fenced blocks

Refs infiniflow#15482

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

### Testing

- `ruff check deepdoc/parser/markdown_parser.py
test/unit_test/deepdoc/parser/test_markdown_parser.py`
- `python3 run_tests.py -t
test/unit_test/deepdoc/parser/test_markdown_parser.py`
## Summary
- keep the native Docling chunking path when it returns usable chunks
- fall back to the standard Docling response parser when a chunked
request gets HTTP 200 but returns no usable chunks
- add a regression test for older Docling servers that accept the
chunking request but return a standard conversion payload

## Why
Older external Docling servers can accept a request containing
`do_chunking: true` and still return the standard conversion response
shape. The current code treats any HTTP 200 from the chunked request as
a native chunk response, finds no chunk entries, and returns zero
sections without trying the standard response parser.

Fixes infiniflow#15569.

## Validation
- `python -m pytest
test\\unit_test\\deepdoc\\parser\\test_docling_parser_remote.py -q`
- `python -m py_compile deepdoc\\parser\\docling_parser.py
test\\unit_test\\deepdoc\\parser\\test_docling_parser_remote.py`
- `python -m ruff check deepdoc\\parser\\docling_parser.py
test\\unit_test\\deepdoc\\parser\\test_docling_parser_remote.py`
- `git diff --check`
…infiniflow#15597)

## Summary

Migrate the stop parse documents endpoint from Python to Go.

### Python endpoint
`POST /api/v1/datasets/<dataset_id>/documents/stop` —
`api/apps/restful_apis/document_api.py:1542-1641`

### Changes
| File | Change |
|------|--------|
| `internal/dao/task.go` | Add `GetByDocID` method |
| `internal/dao/task_test.go` | 3 DAO tests (new file) |
| `internal/service/document.go` | Add `StopParseDocuments` + refactor
shared helpers |
| `internal/service/document_test.go` | 8 service tests |
| `internal/handler/document.go` | Add handler + request struct +
interface |
| `internal/handler/document_test.go` | 5 handler tests |
| `internal/router/router.go` | Add `POST /:dataset_id/documents/stop`
route |

### How it works
1. Validates all document IDs belong to the dataset
2. For each document in RUNNING/CANCEL state (or with unfinished tasks):
- Sets Redis cancel signal `{task_id}-cancel` for each associated task
   - Updates `document.run` to CANCEL ("2")
3. Returns `{"success_count": N, "errors": [...]}`

### Test strategy
- **DAO/Service**: SQLite in-memory DB, zero mocks. Redis is nil-safe by
design.
- **Handler**: `fakeDocumentService` implementing `documentServiceIface`
interface.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
…w#15629)

## Summary

Implement the `GET /api/v1/agents/<agent_id>/versions` endpoint in Go,
listing all version snapshots for an agent canvas in descending update
time order.

### Changes

- **New**: `internal/dao/user_canvas_version.go` —
`UserCanvasVersionDAO` with `ListByCanvasID` (ordered by update_time
DESC) and `GetByID`
- **Modified**: `internal/service/agent.go` — Added `CheckCanvasAccess`,
`ListVersions`, `GetVersion` methods
- **Modified**: `internal/handler/agent.go` — Added `ListAgentVersions`
handler with auth check
- **Modified**: `internal/router/router.go` — Registered `GET
/:agent_id/versions` route
- **New**: `internal/service/agent_test.go` — 5 service-level tests
(SQLite in-memory DB, zero mock)
- **Modified**: `internal/handler/agent_test.go` — 3 handler-level tests
(real DB, pre-authenticated context)

### Testing

All 8 tests pass with zero mocking (in-memory SQLite replaces MySQL):

```
=== RUN   TestListVersions_Success         --- PASS
=== RUN   TestListVersions_Empty           --- PASS
=== RUN   TestCheckCanvasAccess_Owner      --- PASS
=== RUN   TestCheckCanvasAccess_NotOwner   --- PASS
=== RUN   TestCheckCanvasAccess_NotFound   --- PASS
=== RUN   TestListAgentVersionsHandler_Success      --- PASS
=== RUN   TestListAgentVersionsHandler_NoPermission --- PASS
=== RUN   TestListAgentVersionsHandler_CanvasNotFound --- PASS
```

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
### What problem does this PR solve?

Not display `success` when check not passed.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
…#15633)

## Summary

Implement the `POST /api/v1/agents/<agent_id>/upload` endpoint in Go,
allowing file uploads associated with agent canvases.

### Changes

- **Modified**: `internal/service/agent.go` — Added `CheckCanvasAccess`
method (owner + team-level permission semantics)
- **Modified**: `internal/handler/agent.go` — Added `UploadAgentFile`
handler with auth check, multipart file parsing, and delegation to
`FileService`. Added `fileUploader` interface for testability.
- **Modified**: `internal/router/router.go` — Registered `POST
/:agent_id/upload` route
- **Modified**: `cmd/server_main.go` — Wired `fileService` into
`AgentHandler`
- **New**: `internal/service/agent_test.go` — 4 service-level tests for
`CheckCanvasAccess` (owner, team member, private denial, not found)
- **New**: `internal/handler/agent_upload_test.go` — 3 handler-level
tests (success with fake file service, cross-user denial, empty file
rejection)

### Testing

All 7 tests pass with zero mocking of the DB layer (in-memory SQLite):

```
=== RUN   TestCheckCanvasAccess_Owner               --- PASS
=== RUN   TestCheckCanvasAccess_NotOwner            --- PASS
=== RUN   TestCheckCanvasAccess_PrivateCanvas_Denied --- PASS
=== RUN   TestCheckCanvasAccess_NotFound            --- PASS
=== RUN   TestUploadAgentFileHandler_Success        --- PASS
=== RUN   TestUploadAgentFileHandler_NoPermission   --- PASS
=== RUN   TestUploadAgentFileHandler_NoFiles        --- PASS
```

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
### What problem does this PR solve?
This change ensures `/searchbots/ask` receives `search_id` from the
frontend, so the backend can load the matching search configuration when
the shared search flow invokes the endpoint.

### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
…flow#15627)

### What problem does this PR solve?

As Title

### Type of change

- [x] Refactoring
### What problem does this PR solve?
When a document is rerun or updated concurrently, the previous
unconditional update could overwrite a newer task state.
This change adds an `update_time`-based optimistic lock so the update
only succeeds if the record has not been modified by another flow in the
meantime.

### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
…PI (infiniflow#15640)

## Summary

Implement the `GET /api/v1/agents/<agent_id>/versions/<version_id>`
endpoint in Go, returning full version details including DSL.

Depends on infiniflow#15629 which introduced the version list endpoint and
`UserCanvasVersionDAO` infrastructure.

### Changes

- **Modified**: `internal/handler/agent.go` — Added `GetAgentVersion`
handler with auth check and ownership verification
- **Modified**: `internal/router/router.go` — Registered `GET
/:agent_id/versions/:version_id` route
- **New/Modified tests**: Service and handler tests for the version
detail endpoint

### Testing

```
=== RUN   TestGetVersion_Success       --- PASS
=== RUN   TestGetVersion_WrongCanvas   --- PASS
=== RUN   TestGetVersion_NotFound      --- PASS
=== RUN   TestGetAgentVersionHandler_Success      --- PASS
=== RUN   TestGetAgentVersionHandler_VersionNotFound --- PASS
```

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Harry-Hz-Zhang and others added 18 commits June 15, 2026 14:06
…infiniflow#16010)

### Description
- **Refactor**: Replaced `utility.GenerateUUID1` (UUID v1) with
`utility.GenerateToken` (UUID v4) for generating entity IDs (`userID`,
`kbID`, `modelID`, etc.).

- **Cleanup**: Removed the unused `GenerateUUID1` function from
`utility` package.

- **Improvement**: Simplified ID generation logic and eliminated
unnecessary error handling boilerplate since `GenerateToken` cannot
fail.
### What problem does this PR solve?

as title.

### Type of change

- [x] Refactoring

Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve?

```
RAGFlow(api/default)> parse file 'README.md';
Parsing Markdown file: README.md
--- AST tree:
HTMLBlock '<div align="center">\n<a href="https:…'
```

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve?

As title

### Type of change

- [x] Other (please describe): add some models
### What problem does this PR solve?

```
RAGFlow(api/default)> list supported models from 'longcat' 'test'
+-----------+------------+---------------+------------+-------------+-----------------------------+----------+
| dimension | dimensions | max_dimension | max_tokens | model_types | name                        | thinking |
+-----------+------------+---------------+------------+-------------+-----------------------------+----------+
|           |            |               |            |             | LongCat-2.0-Preview@LongCat |          |
|           |            |               |            |             | LongCat-2.0-Preview@LongCat |          |
+-----------+------------+---------------+------------+-------------+-----------------------------+----------+

# Fixed:

RAGFlow(api/default)> list supported models from 'longcat' 'test'
+------------+---------------+------------+-------------+-----------------------------+----------+
| dimensions | max_dimension | max_tokens | model_types | name                        | thinking |
+------------+---------------+------------+-------------+-----------------------------+----------+
|            |               |            |             | LongCat-2.0-Preview@LongCat |          |
+------------+---------------+------------+-------------+-----------------------------+----------+
```

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
…low#15509)

Guard the agent-attachment download against a missing or empty storage blob so the caller gets a structured 4xx (`Document not found!`) instead of an HTTP 500. Same bug class as infiniflow#15365 on document preview.
Resolve infiniflow#15502
### What problem does this PR solve?

```
RAGFlow(api/default)> parse file 'test.html';
Parsing HTML file: test.html
  <html>
......
```

Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve?

As title.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve?

Fix: Adjust chat line height.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
Fix one data source can be synced to multiple dataset
Test add/delete - worked.
…finiflow#16024)

### What problem does this PR solve?

Feat: Move less important chat settings into a collapsible panel.

### Type of change


- [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve?

Feat:
- Allow upsert model_type for instance model

Fix:
- Allow create instance with duplicate api_key

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve?

Feat: Add edit model type function

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

go-version of Pregel-based BSP engine

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
…w#16019)

### What problem does this PR solve?

As title

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve?
Adds a legacy mode for /chat/completions that restores v0.23.0-style
output by converting start_to_think/end_to_think back into raw
<think></think> markers and streaming cumulative answer text.

### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?
Fixes the sandbox config API method mismatch so the frontend and backend
use the same HTTP verb.

### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
…5943)

The cl100k_base encoding cache is shipped in the image at
/ragflow/<sha1-of-url>, but tiktoken only uses it when TIKTOKEN_CACHE_DIR
points at /ragflow. That env var was previously set only as an import
side-effect of common/token_utils.py, so any code path that touched
tiktoken before that import (e.g. rag/app/resume.py at module load) fell
back to downloading from openaipublic.blob.core.windows.net and crashed
in air-gapped deployments.

- Dockerfile: set ENV TIKTOKEN_CACHE_DIR=/ragflow so the cache is used by
  every process from container start, regardless of import order.
- common/token_utils.py: use os.environ.setdefault so an operator-provided
  TIKTOKEN_CACHE_DIR is preserved.
- rag/app/resume.py: widen the optional-tiktoken guard from ImportError to
  Exception so a missing cache + no network degrades gracefully instead of
  breaking module import.
- add regression tests for the cache-dir configuration.
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jun 16, 2026
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR fixes a startup crash in air-gapped environments where tiktoken attempts to download encoding files from openaipublic.blob.core.windows.net. The Dockerfile now sets TIKTOKEN_CACHE_DIR=/ragflow, token_utils.py uses os.environ.setdefault to preserve operator-supplied values, resume.py catches all exceptions on encoding load, and regression tests cover the new cache-dir logic.

Changes

Offline tiktoken cache fix

Layer / File(s) Summary
TIKTOKEN_CACHE_DIR wiring
Dockerfile, common/token_utils.py
Dockerfile sets TIKTOKEN_CACHE_DIR=/ragflow so tiktoken locates the pre-bundled cache without network access. token_utils.py replaces an unconditional variable assignment with os.environ.setdefault(...) so any operator-supplied value is preserved while the project base directory is used as the default.
Broader exception handling in encoding load
rag/app/resume.py
The tiktoken.encoding_for_model(...) call now catches Exception instead of only ImportError, falling back to _tiktoken_encoding = None when cached model data is absent or the network is unreachable.
Regression tests for cache-dir behavior
test/unit_test/common/test_token_utils.py
Adds import importlib and import os, and introduces TestTiktokenCacheDir with four methods that reload common.token_utils under controlled TIKTOKEN_CACHE_DIR states to assert default assignment, non-override, and encoder usability.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 No more network hops at dawn,
The cache sits right where it belongs.
setdefault keeps your value strong,
Exceptions caught before they go wrong.
The rabbit hops offline — all along! 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main objective: preventing tiktoken from attempting network downloads during offline startup.
Description check ✅ Passed The description fully addresses the template with problem statement, detailed explanation of the fix, verification steps, and type of change clearly marked.
Linked Issues check ✅ Passed All code changes directly address issue #15943: Dockerfile sets TIKTOKEN_CACHE_DIR, token_utils.py uses setdefault to preserve operator settings, resume.py broadens exception handling, and tests verify cache configuration.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the offline startup failure. No unrelated modifications or feature creep detected in the four files modified.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/app/resume.py`:
- Around line 49-53: The fallback exception handler that sets
`_tiktoken_encoding` to `None` lacks logging to record this failure mode.
Additionally, when `_tiktoken_encoding` is `None`, the `_text_shingles()`
function returns empty sets for all inputs, which causes the
`_shingling_jaccard()` function to incorrectly return `1.0` for empty unions,
treating distinct texts as duplicates. To fix this: first, add logging to the
exception handler in the try-except block where `_tiktoken_encoding` is assigned
`None` to record the encoding initialization failure with relevant error
details. Second, in the `_shingling_jaccard()` function, explicitly handle the
case where both input shingle sets are empty to return an appropriate value
(such as `0.0` for distinct texts or a neutral value) instead of returning
`1.0`, ensuring that the dedup checks at lines 1960 and 2019 do not incorrectly
mark distinct texts as duplicates when encoding is unavailable.

In `@test/unit_test/common/test_token_utils.py`:
- Around line 379-421: The TestTiktokenCacheDir class is missing a required
pytest priority marker that is enforced for all tests under test/**/*.py. Add a
pytest priority marker decorator (`@pytest.mark.p1`, `@pytest.mark.p2`, or
`@pytest.mark.p3`) above the TestTiktokenCacheDir class definition to specify the
test priority level for these regression tests. Choose the appropriate priority
level based on the criticality of the offline tiktoken cache configuration
functionality.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 33e87d1b-a0f8-458c-842c-e5cefc52be49

📥 Commits

Reviewing files that changed from the base of the PR and between ee1c503 and 4359470.

📒 Files selected for processing (4)
  • Dockerfile
  • common/token_utils.py
  • rag/app/resume.py
  • test/unit_test/common/test_token_utils.py

Comment thread rag/app/resume.py
Comment on lines +49 to 53
except Exception:
# Besides ImportError, loading the encoding can fail when the cached
# cl100k_base file is missing and the network is unavailable (#15943).
# Fall back to the heuristic path instead of breaking module import.
_tiktoken_encoding = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read-only verification: confirm the reachable path and downstream dedup coupling.
rg -n -C2 '_tiktoken_encoding = None|def _text_shingles|def _shingling_jaccard|if not union|jac > 0.5' rag/app/resume.py

Repository: infiniflow/ragflow

Length of output: 1106


🏁 Script executed:

# View _text_shingles and _shingling_jaccard implementations
sed -n '2713,2760p' rag/app/resume.py

Repository: infiniflow/ragflow

Length of output: 1375


Add logging to the fallback path and fix the Jaccard similarity logic for the None-encoding case.

When _tiktoken_encoding is None, _text_shingles() returns empty sets for all inputs. The current Jaccard implementation then returns 1.0 for empty unions (Line 2750), treating any pair of distinct texts as duplicates when encoding is unavailable (Lines 1960 and 2019 dedup checks). The fallback exception handler also lacks logging despite representing a new failure mode.

Suggested fix
+import logging
 try:
     import tiktoken
     _tiktoken_encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
-except Exception:
+except Exception as e:
     # Besides ImportError, loading the encoding can fail when the cached
     # cl100k_base file is missing and the network is unavailable (`#15943`).
     # Fall back to the heuristic path instead of breaking module import.
+    logging.getLogger(__name__).warning(
+        "tiktoken encoding unavailable; using heuristic fallback: %s", e
+    )
     _tiktoken_encoding = None

In _shingling_jaccard(), explicitly handle the empty-shingle case:

 def _shingling_jaccard(text1: str, text2: str, n: int = 5) -> float:
     s1 = _text_shingles(text1, n=n)
     s2 = _text_shingles(text2, n=n)
+    if not s1 and not s2:
+        return 1.0
+    if not s1 or not s2:
+        return 0.0
     union = s1 | s2
     if not union:
-        return 1.0
+        return 0.0
     return len(s1 & s2) / len(union)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
except Exception:
# Besides ImportError, loading the encoding can fail when the cached
# cl100k_base file is missing and the network is unavailable (#15943).
# Fall back to the heuristic path instead of breaking module import.
_tiktoken_encoding = None
import logging
try:
import tiktoken
_tiktoken_encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
except Exception as e:
# Besides ImportError, loading the encoding can fail when the cached
# cl100k_base file is missing and the network is unavailable (`#15943`).
# Fall back to the heuristic path instead of breaking module import.
logging.getLogger(__name__).warning(
"tiktoken encoding unavailable; using heuristic fallback: %s", e
)
_tiktoken_encoding = None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/app/resume.py` around lines 49 - 53, The fallback exception handler that
sets `_tiktoken_encoding` to `None` lacks logging to record this failure mode.
Additionally, when `_tiktoken_encoding` is `None`, the `_text_shingles()`
function returns empty sets for all inputs, which causes the
`_shingling_jaccard()` function to incorrectly return `1.0` for empty unions,
treating distinct texts as duplicates. To fix this: first, add logging to the
exception handler in the try-except block where `_tiktoken_encoding` is assigned
`None` to record the encoding initialization failure with relevant error
details. Second, in the `_shingling_jaccard()` function, explicitly handle the
case where both input shingle sets are empty to return an appropriate value
(such as `0.0` for distinct texts or a neutral value) instead of returning
`1.0`, ensuring that the dedup checks at lines 1960 and 2019 do not incorrectly
mark distinct texts as duplicates when encoding is unavailable.

Source: Coding guidelines

Comment on lines +379 to +421
class TestTiktokenCacheDir:
"""Regression tests for the offline tiktoken cache configuration (#15943).

The container ships the cl100k_base encoding cache under the project root,
so ``common.token_utils`` must make tiktoken use it via ``TIKTOKEN_CACHE_DIR``
instead of reaching out to ``openaipublic.blob.core.windows.net`` at runtime.
"""

def test_import_sets_cache_dir_when_unset(self, monkeypatch):
"""Importing the module sets TIKTOKEN_CACHE_DIR to the project root."""
import common.token_utils as token_utils
from common.file_utils import get_project_base_directory

monkeypatch.delenv("TIKTOKEN_CACHE_DIR", raising=False)
importlib.reload(token_utils)

assert os.environ.get("TIKTOKEN_CACHE_DIR") == get_project_base_directory()

def test_import_does_not_override_existing_cache_dir(self, monkeypatch, tmp_path):
"""An operator-provided TIKTOKEN_CACHE_DIR must be preserved (setdefault)."""
import common.token_utils as token_utils

custom_dir = str(tmp_path)
monkeypatch.setenv("TIKTOKEN_CACHE_DIR", custom_dir)
importlib.reload(token_utils)

assert os.environ.get("TIKTOKEN_CACHE_DIR") == custom_dir

def test_encoder_available_after_reload(self, monkeypatch):
"""The module-level encoder still loads correctly via the cache path."""
import common.token_utils as token_utils

monkeypatch.delenv("TIKTOKEN_CACHE_DIR", raising=False)
importlib.reload(token_utils)

assert token_utils.encoder is not None
assert token_utils.num_tokens_from_string("hello") == 1

def teardown_method(self):
"""Reload once more so other test modules see a clean module state."""
import common.token_utils as token_utils

importlib.reload(token_utils)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add the required pytest priority marker to the new regression test class.

The new tests are unmarked, but this repo requires p1/p2/p3 markers under test/**/*.py.

✅ Suggested update
+@pytest.mark.p1
 class TestTiktokenCacheDir:

As per coding guidelines, test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python testing.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit_test/common/test_token_utils.py` around lines 379 - 421, The
TestTiktokenCacheDir class is missing a required pytest priority marker that is
enforced for all tests under test/**/*.py. Add a pytest priority marker
decorator (`@pytest.mark.p1`, `@pytest.mark.p2`, or `@pytest.mark.p3`) above the
TestTiktokenCacheDir class definition to specify the test priority level for
these regression tests. Choose the appropriate priority level based on the
criticality of the offline tiktoken cache configuration functionality.

Source: Coding guidelines

@JinHai-CN

Copy link
Copy Markdown
Member

@18062706139fcz would you please resolve the conflicts?

@JinHai-CN JinHai-CN self-assigned this Sep 9, 2026
@yuzhichang yuzhichang closed this Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. 🌈 python Pull requests that update Python code size:S This PR changes 10-29 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Failed to resolve 'openaipublic.blob.core.windows.net' ([Errno -2] Name or service not known)"))